将多个整数存储在字符串中
Storing multiple integers in a string
我试图将5个整数存储到一个字符串中,但是我遇到了麻烦。这是代码:
for (int a = 0; a < 5; a++)
{
string ans;
int number;
int num;
number = rand() % 9 + 1;
cout << number << " ";
num = number;
to_string(num);
ans =+ num;
}
本质上,我希望" Ans"成为" 12345"的线条,但是当我运行它时,它不会显示任何内容,或者在其中显示了5个带有问号的盒子。有帮助吗?
您可以做这样的事情:
string ans;
int number;
for (int a = 0; a < 5; a++){
number = rand() % 9 + 1;
ans += to_string(number);
}
cout << ans;
to_string()
返回字符串。您可以尝试做: ans += to_string(num);
或,编写代码以提高可读性的更好方法是使用临时字符串变量而不是int num
存储数字。
string temp;
string ans;
for (int a = 0; a < 5; a++)
{
//string ans;
int number;
//int num;
number = rand() % 9 + 1;
cout << number << " ";
//num = number;
temp = to_string(number);
ans += temp;
}
您不想在for循环中声明您的string ans
,因为每次循环运行时,您的ans
都不会再持有上一个值,因为它再次被声明。
您的代码有许多问题。
-
您在循环内声明
ans
,因此在每个环路迭代中都会创建和破坏。如果您希望循环将5个数字附加到ans
,则必须在循环之外声明。 -
std::to_string()
输出新的std::string
作为其返回值。它不会像代码所假设的那样"神奇地"将输入值转换为字符串类型。您根本没有将返回的字符串附加到ans
。 -
=+
不是有效的附录操作员。它被解释为单独的操作员=
和+
。std::string
没有将int
作为输入的=
运算符,并且没有一单元+
操作员。您需要使用+=
操作员。
尝试以下操作:
#include <string>
#include <iostream>
std::string ans;
for (int a = 0; a < 5; ++a)
{
int number = ...
...
ans += std::to_string(number);
}
// use ans as needed...
或者,使用std::ostringstream
代替std::to_string()
:
#include <string>
#include <sstream>
#include <iostream>
std::ostringstream oss;
for (int a = 0; a < 5; ++a)
{
int number = ...
...
oss << number;
}
std::string ans = oss.str();
// use ans as needed...
话虽如此,您显然使用C 11(当引入std::to_string()
时)或更高版本,因此您应该使用C 随机数生成器而不是C,例如:
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 9);
for (int a = 0; a < 5; ++a)
{
int number = dis(gen);
...
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 将字符串存储到文件下一行的变量中
- 将字符串存储在 constexpr 结构中
- 将字符串存储为十六进制而不进行转换
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将非数字字符串存储为二进制整数
- 将 C++ 字符串存储到 char* 向量中
- C++无法将对齐的字符串存储在字符串变量中并打印出来
- 短(ASCII,每个字符 7 位)字符串存储和C++中的比较优化
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何将此字符串存储为不同的变量
- C 将字符串存储到类中
- C :占用更多内存,将单个字符作为char或字符串存储
- 排序通过字符串C 存储在向量的对象
- 如何将可变长度字符串存储在C/C 中
- 将字符串存储在无符号长整型的向量中
- 如何使用模板解码将来自 YAML::Node 的字符串存储在类中
- 将字符串存储到数组中
- C++-将用逗号分隔的用户输入字符串存储到向量中