我创建了一个函数来将 Int 转换为字符串、建议、评论等:)

I made a function to convert an Int to a String, Advice, comments, etc :)

本文关键字:字符串 转换 建议 评论 Int 创建 函数 一个      更新时间:2023-10-16

好的,所以我有一个小项目,我遇到了必须将 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);