将整数放入字符串中

putting an integer into a string

本文关键字:字符串 整数      更新时间:2023-10-16

我试图通过将整数的数字分开并按顺序将它们放入大小为 3 的字符串中来将整数放入字符串中

这是我的代码:

char pont[4];
void convertInteger(int number){
int temp100=0;
int temp10=0;
int ascii100=0;
int ascii10=0;
if (number>=100) {
    temp100=number%100;
    ascii100=temp100;
    pont[0]=ascii100+48;
    number-=temp100*100;
    temp10=number%10;
    ascii10=temp10;
    pont[1]=ascii10+48;
    number-=temp10*10;
    pont[2]=number+48;
}
if (number>=10) {
    pont[0]=48;
    temp10=number%10;
    ascii10=temp10;
    pont[1]=ascii10+48;
    number-=temp10*10;
    pont[2]=number+48;
}
else{
    pont[0]=48;
    pont[1]=48;
    pont[2]=number+48;
}
}

下面是应该发生的情况的示例:

number = 356
temp100 = 356%100 = 3
ascii100 = 3
pont[0]= ascii100 = 3
temp100 = 3*100 = 300
number = 365 - 300 = 56
temp10 = 56%10 = 5
ascii10 = 5
pont[1]= ascii10 = 5
temp10 = 5*10 = 50
number = 56 - 50 = 6
pont[2]=6

我可能在某处遇到错误并且看不到它(不知道为什么)......顺便说一下,这应该是C++的。 我可能会把它和 C 语言混为一谈......提前致谢

可能是你现在忽略的错误:

    pont[2]=number+48;
}
if (number>=10) {    /* should be else if */
    pont[0]=48;

但是,我想建议一种不同的方法;您不在该值高于10010等,因为0仍然是一个有用的值 - 如果您不介意将答案填充零。

请考虑以下数字:

int hundreds = (number % 1000) / 100;
int tens = (number % 100) / 10;
int units = (number % 10);

所有内置类型都知道如何向std::ostream表示自己。它们可以格式化为精度,转换为不同的表示形式等。

这种统一的处理允许我们将内置内容写入标准输出:

#include <iostream>
int main()
{
    std::cout << 356 << std::endl; // outputting an integer
    return 0;
}

输出:

356

我们可以流式传输到不仅仅是 cout .有一个名为 std::ostringstream 的标准类 ,我们可以像cout一样使用它,但它给了我们一个可以转换为字符串的对象,而不是将所有内容发送到标准输出:

#include <sstream>
#include <iostream>
int main()
{
    std::ostringstream oss;
    oss << 356;
    std::string number = oss.str(); // convert the stream to a string
    std::cout << "Length: " << number.size() << std::endl;
    std::cout << number << std::endl; // outputting a string
    return 0;
}

输出:

Length: 3
356