使用.txt文件填充 STL 列表不起作用

Filling a STL list with a .txt file not working

本文关键字:列表 不起作用 STL 填充 txt 文件 使用      更新时间:2023-10-16

使用文本文件中的数据填充 STL 列表失败。

Lexicon::Lexicon(const string &fileName) {
    string tmp;
    ifstream readFile;
    readFile.open(fileName.c_str());
    if (readFile.is_open()) {
        cout << "File Is Open" << endl;
        while (readFile >> tmp) {
            list<string>::const_iterator i;
            for (i = Words.begin(); i != Words.end(); ++i) {
                Words.push_back(tmp);
            }
            readFile.close();
        }
    } else
    {
        cout<<"File Is NOT Open"<<endl;
    }
}
string fileName = "wordsScrambled1.txt"; // in the main
Lexicon hello(fileName);

程序失败并显示消息"文件未打开">,并以代码 0 退出。

在这个问题因 mcve 而结束之前,我想指出你犯的一些错误。第一个显然是路径或权限问题,即您无法打开输入文件。一旦你克服了这一点,你可能在解析文件时犯了一个错误。您假设 " " 之间的所有字符都表示一个单词。除了行中的最后一个单词之外,所有单词都可能出现这种情况。因此,您最好使用std::getline并使用std::istringstream进行解析。 最后,就像Sam在评论部分指出的那样,你有一个for循环,在崩溃之前无法合理地满足它的退出标准。只需push_back当前元素并继续下一个元素即可。下面是一个快速示例。

Lexicon::Lexicon(const std::string &fileName)
{
    std::ifstream readFile(fileName.c_str());
    if (readFile.is_open())
    {
        std::string line;
        while (std::getline(readFile, line))
        {
            std::istringstream iss(line);
            std::string word;
            while (iss >> word)
            {
                Words.push_back(word);
            }
        }
        readFile.close();
    }
    else
    {
        std::cout << "File Is NOT Open" << std::endl;
    }
}