将多个整数存储在字符串中

Storing multiple integers in a string

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

我试图将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);
    ...
}