前两天电脑出了问题,今日续上
问题:统计文本中单词出现的次数,并输出所在行号,及该行内容
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
using namespace std;
int main()
{
ifstream ifile;
char buf[1000]={'\0'};
ifile.open("poet.txt",ios::in);
map<string,int>map_word_times;
vector<string>lines;
int line_num=1;
int temp_line=0;
string inputs;
cout << "input a word to see:";
cin >> inputs;
while(ifile.getline(buf,1000))
{
lines.push_back(buf);
istringstream line(buf);
string s;
int i=1;
while(line >> s)
{
pair<map<string,int>::iterator,bool>judge;
judge = map_word_times.insert(pair<string,int>(s,i));
if(judge.second!=1)
{
map_word_times[s]++;
}
if(s==inputs && line_num!=temp_line)
{
cout << "It appears in line" << line_num << endl;
cout << buf << endl;
temp_line=line_num;
}
}
line_num++;
}
cout << "In total, it appears: " << map_word_times[inputs] << "times." << endl;