读取一行(getline())

时间:2009-07-26 19:41:58

标签: c++

这个程序基本上会在.txt文件中搜索一个单词,如果找到它,它会打印行和行号。这是我到目前为止所拥有的。

代码:

#include "std_lib_facilities.h"

int main()
{
    string findword;
    cout << "Enter word to search for.\n";
    cin >> findword;

    char filename[20];
    cout << "Enter file to search in.\n";
    cin >> filename;
    ifstream ist(filename);

    string line;
    string word;
    int linecounter = 1;
    while(getline(ist, line))
    {
     if(line.find(findword) != string::npos){
             cout << line << " " << linecounter << endl;}
     ++linecounter;
     }

     keep_window_open();
}

解决。

4 个答案:

答案 0 :(得分:4)

您正在寻找find

if (line.find(findword) != string::npos) { ... }

答案 1 :(得分:1)

我会按照你的建议做,并将这些行分成由空格分隔的单词或标记,然后在标记列表中搜索所需的关键字。

答案 2 :(得分:0)

确保文本文件中的名称周围没有空格。否则,让ist注意以下几点:

while(ist >> line)
{
 if(line == findword){
         cout << line << " " << linecounter << endl;}
 ++linecounter;
 }

我相信你的名字文件在每一行都包含一个名字。所以使用>>,如果有额外的空格,ist会很小心。

答案 3 :(得分:-1)

您可以使用正则表达式查找该行中的单词。不知道足够的C ++来帮助您了解详细信息。

相关问题