[英]Read end of line while looping word by word in c++
我正在讀一個包含句子列表的文件,我需要讀取每個單詞並嘗試找出這個單詞的行號。該文件包含:
I am for truth
no matter who tells it,
I am for justice,
no matter who it is for or against
Malcom X
我希望輸出采用以下形式:
against 4
matter 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;
infile.open("test.txt" , ios::in);
if(infile.fail())
{
cout<<"Error Opening file"<<endl;
return 0;
}
while(!infile.eof())
{
infile>>word;
for(int i=0 ; i<word.size();i++)
{
if(ispunct(word[i]))
word.erase(i,1);
}
cout<<count<<endl;
if(!bst->search(word))
{
cout<<word<<endl;
bst->insert(word);
cout<<"add"<<endl;
}
else
{
cout<<word<<endl;
cout<<"exist"<<endl;
}
}
infile.close();
return 0;
}
這可能會讓你開始,
#include <string>
#include <fstream>
#include <sstream>
// read the file line by line
int line_number = 0;
string line;
while (getline(infile, line))
{
++line_number;
// put the line in an istringstream
istringstream buffer(line);
// read the words from the line
string word;
while (buffer >> word)
{
// do something with word and line_number
// save them in some data structure
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.