[英]Reading parts of a line (getline())
Basically this program searches a .txt file for a word and if it finds it, it prints the line and the line number. 基本上,该程序在.txt文件中搜索单词,如果找到该单词,它将打印行和行号。 Here is what I have so far.
这是我到目前为止所拥有的。
Code: 码:
#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();
}
Solved. 解决了。
您正在寻找find
:
if (line.find(findword) != string::npos) { ... }
我会按照您的建议进行操作,然后将行分成由空格分隔的单词或标记,然后在标记列表中搜索所需的关键字。
Make sure there are no spaces around the names in your text file. 确保文本文件中名称周围没有空格。 Otherwise, let
ist
take care like the following : 否则,请让
ist
采取以下措施:
while(ist >> line)
{
if(line == findword){
cout << line << " " << linecounter << endl;}
++linecounter;
}
I believe that your names file contains a name on every line. 我相信您的名称文件的每一行都包含一个名称。 so using
>>
, ist
will take care if there are extra spaces. 因此使用
>>
, ist
会注意是否有多余的空格。
You could use a regular expression to find the word in the line. 您可以使用正则表达式在行中查找单词。 Don't know enough C++ to help you with the details.
对C ++的了解不足,无法为您提供详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.