簡體   English   中英

為什么cout不顯示字符串變量rnd?

[英]Why does cout not display the string variable rnd?

當我嘗試顯示帶有cout的隨機生成的字符串rnd時,我僅獲得結尾行作為輸出。 為什么會這樣,我該如何解決? 另外,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;
}

添加rnd.resize(str.size()); cin >> str; rnd不包含任何字符,因此您需要將字符串調整為與str相同的大小。

您永遠不會更改rnd的大小,因此它將始終為0。當i> rnd.size()是不確定的行為時,設置(或獲取)rnd [i],即使它“起作用”(例如,因為您的實現使用短字符串優化,而您的所有單詞都很短),因為str == rnd的大小是不同的,所以永遠不會這樣。

我建議:

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

在最初的建設中。 while循環內,可以使用rnd[i]因為rnd的大小正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM