1

我试图通过分隔其数字并将它们按顺序放入大小为 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 语言混为一谈...在此先感谢

4

2 回答 2

1

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

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

但是,我想提出一种不同的方法;您不在乎该值是否高于100,10等,因为0它仍然是一个有用的值 - 如果您不介意零填充您的答案。

考虑以下数字:

int hundreds = (number % 1000) / 100;
int tens = (number % 100) / 10;
int units = (number % 10);
于 2012-05-01T23:23:34.137 回答
1

所有内置类型都知道如何将自己表示为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
于 2012-05-02T11:31:47.487 回答