【问题标题】:Why does cout not display the string variable rnd?cout为什么不显示字符串变量rnd?
【发布时间】:2012-10-11 04:54:05
【问题描述】:

当我尝试使用 cout 显示随机生成的字符串 rnd 时,我只得到 endlines 作为输出。为什么会这样,我该如何解决?附带说明一下,while 语句会创建一个无限循环。我没有正确比较字符串吗?我正在使用 g++ 编译器。

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{
    string str;
    string rnd;
    int x;

    cout << "What do you want the string to be?" << endl;
    cin >> str;

    srand(1);

    //assign the initial random string
    for(int i = 0; i < str.size(); i++)
    {
        x = rand() % 26 + 97;
        rnd[i] = static_cast<char>(x);
    }

    cout << rnd << endl;

    //change individual characters of the string rnd until rnd == str
    while(str != rnd)
    {
        for(int i = 0; i < str.size(); i++)
        {
            if (rnd[i] == str[i])
            {
                continue;
            }
            else
            {
                x = rand() % 26 + 97;
                rnd[i] = static_cast<char>(x);
            }
        }

        cout << rnd << endl;
    }

    return 0;
}

【问题讨论】:

    标签: c++ string infinite-loop cout


    【解决方案1】:

    cin &gt;&gt; str; 之后添加rnd.resize(str.size());rnd 不包含任何字符,因此您需要将字符串大小调整为与str 相同的大小。

    【讨论】:

      【解决方案2】:

      你永远不会改变rnd 的大小,所以它总是为 0。当 i > rnd.size() 时设置(或获取)rnd[i] 是未定义的行为,但即使它“有效”(比如,因为您的实现使用了短字符串优化并且您的所有单词都很短),所以str == rnd 永远不会出现这种情况,因为它们的大小不同。

      我建议:

      rnd.push_back('a' + rand() % 26);
      

      在最初的建设中。在while 循环内,您可以使用rnd[i],因为此时rnd 具有正确的大小。

      【讨论】:

        猜你喜欢
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-20
        • 2012-07-29
        • 2019-03-04
        • 1970-01-01
        相关资源
        最近更新 更多