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

C++ Read words and lines in same reading loop

我已经了解如何从文本文件中查找和阅读单词。我也了解如何使用 getline() 浏览文本并阅读特定行。

但现在我想弄清楚如何在同一个地方使用两者 "reading loop"。

会是这样的:

    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 操作是否成功,虽然它以您实现它的方式工作,但它并不是您真正想要的。

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

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

所以对于你的情况,这样的事情会做:

#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)
    {
        /* ... */
    }
}

或者,您也可以实例化 stringstream 对象一次并调用其 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)
    {
        /* ... */
    }
}

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