好吧,我有一个迷你项目,我遇到了必须将 int 转换为字符串才能像处理任何其他字符串一样遍历它的问题。我找到了一些通过包含图书馆来在线完成的方法,但我不太喜欢它们。我尝试制作自己的函数,想知道这是否合适。
到目前为止,它只接受正数,并且它们应该只在 C++ 必须提供的最大整数范围内,大约 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);
关于c++ - 我创建了一个将 Int 转换为 String、建议、评论等的函数 :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216347/