C++在同一个阅读循环中阅读单词和行



我已经了解了如何从文本文件中查找和读取单词。我也理解如何使用getline()遍历文本并读取某一行。

但现在我正试图弄清楚如何在同一个"阅读循环"中使用这两种方法。

它应该是这样的:

    string S1="mysearchword01",S2="mysearchword02";
    char word[50];
    while(myfile.good()){  //while didn't reach the end line
         file>>word; //go to next word
         if (word==S1){ //if i find S1 I cout the two next words
             file>>a>>b;
             cout<<a<<" "<<b<<endl;}
             }
         else if (word==S2) {
            //****here I want to cout or save the full line*****    
             }
    }

那么我可以用getline吗?

提前谢谢。

std::fstream::good()检查上一次I/O操作是否成功,尽管它以您实现它的方式工作,但它并不是您真正想要的。

使用getline(file, stringToStoreInto)代替while循环中对good()的调用,当到达文件末尾时,它也将返回false。

EDIT:要从std::getline()中获得的行中提取单个以空格分隔的元素(单词),可以使用std::stringstream,用行字符串初始化它,然后使用>>运算符将该字符串流中的单个单词提取到另一个"单词"字符串中。

因此,对于您的情况,可以使用类似的方法:

#include <sstream>
std::string line, word;
while (getline(file, line))
{
    std::stringstream ss(line);
    ss >> word;
    if (word == S1)
    {
        // You can extract more from the same stringstream
        ss >> a >> b;
    }
    else if (word == S2)
    {
        /* ... */
    }
}

或者,您也可以实例化字符串流对象一次并调用其str()方法,其中一个重载重置流,而另一个重载替换其内容。

#include <sstream>
std::stringstream ss;
std::string line, word;
while (getline(file, line))
{
    ss.str(line); // insert / replace contents of stream
    ss >> word;
    if (word == S1)
    {
        // You can extract more from the same stringstream
        ss >> a >> b;
    }
    else if (word == S2)
    {
        /* ... */
    }
}

您可以使用字符串流提取多个单词,而不仅仅是第一个,只需像以前一样继续调用operator>>即可。

最新更新