字符串向量中的混搭数据

问题描述

我一直在努力解决这个问题,

我有一个程序可以从提供的字典(txt 文件)中随机输入一个单词, 然后将此单词添加到字符串向量中。

randomWord() 函数按预期工作,但是当我尝试打印向量时 getWords() 似乎混搭了所有内容

向量声明:

vector<string> pass_words; //Array of words used in password

这是两个函数

//gets a random word from the wordlist file.
string randomWord()
{
    wordfile.open ("wordlist.txt"); //open the wordlist file
    string wordonline;
    string word;
    int wordwant = rand()%58110; //Maximum is 58109 which is the last word,minimum is 0.
    for (int linenum = 0; getline (wordfile,wordonline) && linenum <(wordwant+1) ; linenum++) {
        if (linenum == wordwant) {
            word = wordonline;
        }
    }
    wordfile.close();
    return word;
}

// gets random words based on number of words supplied.
void getWords() {
    cout << "WORD GET" << endl;
    string thisword;
    for (int i=0 ; i<num_words; i++) {
        thisword = randomWord();
        pass_words.push_back(thisword) ;
        cout << pass_words[i] << " " ; //debugging
    }
    cout << endl; //debugging
    return;
}   

这是一个示例输出

WORD GET
 posingdsate

我做错了什么? 同样显然,当我为 pass_words 向量放置另一个循环时,我可以看到这些值,但永远不会在 getWords() 函数之后或之内看到。

这是另一个循环的输出

housemaids
--
necessitate
--
contacts
--
kampala
--
pion
--
scooped
--
posing
--

解决方法

您很有可能从 CRLF 分隔的文件中读取 CR 字符,假设它只是 LF 分隔,然后打印它们,其中回车会将光标向左猛击并覆盖现有文本.

您需要将其读作 CRLF 或去除任何 CR 或 LF 字符。

您也可以强制换行:

std::cout << pass_words[i] << std::endl;