我创建了一个函数来将 Int 转换为字符串、建议、评论等:)
I made a function to convert an Int to a String, Advice, comments, etc :)
好的,所以我有一个小项目,我遇到了必须将 int 转换为字符串才能像使用任何其他字符串一样遍历它的问题。我找到了一些通过包括图书馆在线的方法,但我并不真正喜欢它们。我尝试制作自己的功能,并想知道这是否体面。
截至目前,它只接受正数,它们应该只在C++必须提供的最大 int 内,大约 20 亿左右。
在这里:
// ONLY POSITIVE NUMBERS AND THEY MUST BE LESS THAN THE MAX INT
string castIntToString(int number){
// find out how many numbers it has
int numbers = 0;
for (int i = number; i > 0; i/= 10){
numbers++;
}
// generate the place value of the 1st number
int placeValue = 1;
for(int i = 1; i < numbers; i++){
placeValue *= 10;
}
int modValue = placeValue * 10;
// isolate each of those values
// Why is "convertAscii" 48? Becuase character '0' is number 48
int convertAscii = 48, actualValue;
string numString = "";
char actualCharValue;
for (int i = 0; i < numbers; i++){
actualValue = (number % (modValue)) / placeValue;
actualCharValue = actualValue + convertAscii;
numString+= actualCharValue;
placeValue/= 10;
modValue/= 10;
}
return numString;
}
您可以使用
sprintf
在一行中执行此操作
char* str[10]; // The biggest possible int will take up to 10 char in base 10.
snprintf(str, 10, "%d", value); // where value is your int.
如果您使用的是 C++ 11 并且它是string
,则 std::to_string 是一种更简单的方法。
std::string str = to_string(value);
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组