简体   繁体   English

如何从 C++ 中的文本文件中获取特定字符串

[英]How do I get a specific string from a text file in C++

Lets say I have a text file with this input:假设我有一个带有此输入的文本文件:

Caroline went to the sea, and she forgot her boat.卡罗琳去了海边,她忘记了她的船。

Patrick went to the sea, and he drowned.帕特里克去了大海,他淹死了。

How do I get the word sea and the whole line with the word sea?我如何获得单词 sea 和单词 sea 的整行?

So basically when I type sea the output needs to be:所以基本上当我输入sea时,output 需要是:

Caroline went to the sea, and she forgot her boat.卡罗琳去了海边,她忘记了她的船。

Patrick went to the sea, and he drowned.帕特里克去了大海,他淹死了。

This is what I currently have:这是我目前拥有的:

int main () {

  // Create a text string, which is used to output the text file
  string myText;

  // Read from the text file
  ifstream MyReadFile("myfile.txt");

  while (getline (MyReadFile, myText)) {
  // Output the text from the file
    cout << myText;
  }

  // Close the file
  MyReadFile.close();
}

Well, what you just need is to iterate the lines of your file and see if the line contains the word you want.好吧,您只需要迭代文件的行并查看该行是否包含您想要的单词。 If it does, just print the line.如果是这样,只需打印该行。 Here is the core of what you need:这是您需要的核心:

while (getline (MyReadFile, myText)) {
  if(myText.find(yourString)!=std::string::npos){
           cout<<myText<<\n;
  }
}

The if statement checks if it the string yourString (which is "sea" in your example) is a substring of line. if 语句检查字符串yourString (在您的示例中为“sea”)是否为 substring 行。 If it is, it will output the line.如果是,则将 output 行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM