如何在C ++中逐行读取具有多行的文件?

问题描述

我正在尝试读取一个包含多行的文件,其中每一行都有一个单词,然后是一个空格,后跟对该单词的简短描述。

文本文件示例:

hello A type of greeting
clock A device which tells us the time
.

末尾的句号(。)表示没有更多行可读取。

我尝试在getline()函数中使用定界符的方法,但仅成功读取了文件的一行。我想将第一个单词(在第一个空格之前)存储在变量中,例如word,将描述(在第一个空格之后的单词,直到遇到换行符的单词)存储在另一个变量中,例如{{1} }。

我的方法:

desc
上述代码的

输出是:

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main()
{
    string filename = "text.txt" ;
    ifstream file (filename);
    if (!file)
    {
        cout<<"could not find/open file "<<filename<<"\n";
        return 0;
    } 

    string word;
    string desc;
    string line;


    while(file){
        getline(file,line,' ');
        
        word = line;
        break;
    }
    while(file){
        getline(file,'\n');
        desc = line;
        break;
    }    

   file.close();
    cout<<word<<":  ";
    cout<<desc<<"\n";

    return 0;
}

我尝试在上面编写的具有条件hello: A type of greeting 的父循环中添加另一个父循环while,但是该程序从不进入两个子循环。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)