-1
if(inputFile.is_open()){
        while(!inputFile.eof()){
            getline(inputFile, line);
            ss << line;
                while(ss){
                ss >> key;
                cout << key << " ";
                lineSet.insert(lineNumber);
                concordance[key] = lineSet;
            }
            lineNumber++;
        }   
    }

For some reason, the while loop is kicking out after the first iteration and only displays the first sentence of my input file. The rest of the code works fine, I just can't figure out why it thinks the file has ended after the first iteration.

Thanks

4

1 回答 1

0

首先,您应该在不使用 的情况下阅读文件eof,如 πάντα ῥεῖ 注释(请参阅此处以获取解释):

while( getline(inputFile, line) )
{
    // process the line
}

请注意,前面if的内容也不是必需的。

ss假设您之前定义的主要问题stringstream来自逻辑:

ss << line;
while(ss){
    // stuff
}

此处的while循环仅在ss失败时退出。但是你永远不会重新ss回到一个好的状态。因此,尽管您的外部循环确实读取了文件的每一行,但第一行之后的所有行都不会生成任何输出。

相反,您每次都需要重置字符串流:

ss.clear();
ss.str(line);
while (ss) {
    // stuff
}
于 2014-12-01T23:25:43.673 回答