c++ - 我创建了一个将 Int 转换为 String、建议、评论等的函数 :)

标签 c++ string int concatenation string-concatenation

好吧,我有一个迷你项目,我遇到了必须将 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 并且它是 stringstd::to_string是一种更简单的方法。

std::string str = to_string(value);

关于c++ - 我创建了一个将 Int 转换为 String、建议、评论等的函数 :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216347/

相关文章:

c++ - convertTo 在 opencv 中不起作用

c++ - 与我自己的 C++ 库的链接错误

python - .join() 方法到底是做什么的?

java - 拆分字符串并将其放在 int 数组中

mysql - mysql 中 int(11) 列的大小是多少(以字节为单位)?

Swift String to Int 总是返回 nil

c++ - 在 C++ 中向数组添加元素

c++ - 如何将 "this"的生命周期移动到 C++ 中的另一个对象中?

python - Pandas :如何选择具有特定单词的行

java - 检查给定字符串是否与其他两个字符串交错