-1

这是我的代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <iterator>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
string word;
cout << "Insert a name to search for: ";
cin >> word;

ifstream file ("Names.txt");

string line; 
getline(file, line, '.'); 

int i;
for (i = 0; i < line.length(); ++i) {
    if ('A' <= line[i] && line[i] <= 'Z') break;
}

string keyword = line.substr(i);

int cnt = count( istream_iterator<string>(file), istream_iterator<string>(), word);
cout << word << " appears " << cnt << " times. It appears most with " << keyword << ".    keyword" << endl;
return 0;
}

此刻:我可以从包含数千个名称(每行一个)的文本文件中搜索某个名称,然后查看该名称出现了多少次。在每一行上还出现一个带有名称的关键字,它以大写字母开头并以句点结尾。

我的问题:我的代码几乎准备好了,但问题是它从文件的开头搜索关键字然后打印出来(因为我的代码还没有做任何其他事情)

我的目标:我希望它从找到 SEARCH 词的行中搜索关键词。例如,如果我搜索 Juliet,它出现了一个关键字 Girl,那么我希望它使用该关键字而不是文件中的 FIRST 关键字打印名称。

MY THOUGHTS: There should be a way to start searching from the word but I do not know how. Could you help me with making an extra loop so it starts second loop from e.g word Juliet. I don't know how I could convert cin to just a sequence of characters. Since usually when searching for a string in a text file the sequence of characters is between ' symbols.

'Juliet'

but I need to take the word string and somehow convert it

MY QUESTION: How can I convert input word to sequence of characters to get a starting point for a string

4

1 回答 1

0

Something like this? It's not really an 'algorithm' it's just a simple loop.

string word;
cout << "Insert a name to search for: ";
cin >> word;
ifstream file ("Names.txt");
string a_word;
while (file >> a_word && a_word != word)
{
}
if (file)
{
    // found word now start second search.
}
else
{
    // error, didn't find word
}       

Sorry if this isn't right, but I'm struggling to understand what you are stuck on. The above code is very simple, it's simpler than the code you wrote yourself.

于 2013-04-07T20:42:46.923 回答