我正在从文件中读取单词,输出应该是单词和单词出现的行号。我的代码运行良好,但是我在存储每个单词的行号的向量中遇到了问题。
例如,文本文件:
I am for truth
no matter who tells it,
I am for justice,
no matter who it is for or against
Malcom X
我得到的输出:
I 13
am 1133
for 111333444444
truth 1111
no 24
matter 2244
who 222444
tells 2222
it 222224444
justice 3333
is 44444
or 4444444
against 44444444
Malcom 5
X 55
我期待的输出:
against 4
matter 2, 4
am 1, 3
no 2, 4
for 1, 3, 4
or 4
I 1, 3
tells 2
is 4
truth 1
it 2, 4
who 2,4
justice 3
X 5
Malcolm 5
这是我的代码:
int main(int argc, char *argv[]) {
fstream infile ;
BSTFCI <string>* bst = new BSTFCI<string>();
string word;
string line;
vector <string>words;
vector <string>line_no;
int count = 0;
infile.open("test.txt" , ios::in);
if(infile.fail())
{
cout<<"Error Opening file"<<endl;
return 0;
}
while(getline(infile , line))
{
++count;
istringstream buffer(line);
ostringstream counter;
while (buffer >> word)
{
for(int i=0 ; i<word.size();i++) {
if(ispunct(word[i]))
word.erase(i,1);
}
if(!bst->search(word)) {
bst->insert(word);
words.push_back(word);
counter << count;
line_no.push_back(counter.str());
} else {
counter<<count;
for(int k=0;k<words.size();k++) {
if(word==words.at(k))
line_no.at(k)+=counter.str();
}
}
}
}
for(int i=0;i<words.size();i++)
cout << words.at(i) << " " << line_no.at(i) << endl;
infile.close();
return 0;
}