将整数放入字符串中
putting an integer into a string
我试图通过将整数的数字分开并按顺序将它们放入大小为 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;
但是,我想建议一种不同的方法;您不在乎该值高于100
,10
等,因为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
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 如何从C++中的格式化字符串派生整数?
- 如何使用C++将字符串中的字符转换为整数变量
- 向量值(字符串和整数)求和C++
- 如何从字符串C++读取多个整数
- 如何将整数字符串转换为整数的二维向量?
- 输入验证以筛选出字符、字符串和一系列整数
- 有没有办法在C++中将字符串和整数相乘?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- C++字符串大小减去整数不是预期值,为什么?
- 使用字符串流读取整数并将它们相加
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- C++ runtime_exception字符串 + 整数
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- 使用next_permutation函数后如何保存字符串/整数
- 使用fstream和sstream一起从文件中分离字符串/整数