c++ - 在 C++ 中逐字循环时读取行尾

标签 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
    }
}

关于c++ - 在 C++ 中逐字循环时读取行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255403/

相关文章:

c++ - 如何检测代码中的字符串文字?

c++ - 将一个信号连接到两个插槽,但在 Qt 中一次只执行一个插槽

c++ - 为什么auto不能作为函数声明的返回类型

c++ - 使用 QFile 正确读写文件(处理错误等)?

C++错误: Expected constructor,析构函数,或 '(' token 前的类型转换

c++ - << 和 >> 在 C++ 中

c++ - 如何从函数返回 vector 对象?

c++ - 使用 std::ranges 摆脱嵌套的 for 循环

java - 继承会增加耦合吗?

c++ - 为什么在 C++ 中有这么多不同的方法来使用 new 运算符