【问题标题】:How to read a file having multiple lines, line by line in C++?如何在 C++ 中逐行读取具有多行的文件?
【发布时间】:2021-02-03 23:36:54
【问题描述】:

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

文本文件示例:

你好 一种问候 时钟 告诉我们时间的设备 .

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

我尝试了一种在getline() 函数中使用分隔符的方法,但只成功读取了文件的一行。我想将第一个单词(在第一个空格之前)存储在一个变量中,比如word,并将描述(在第一个空格之后的单词,直到遇到换行符)存储在另一个变量中,比如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,line,'\n');
        desc = line;
        break;
    }    

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

    return 0;
}

上述代码的输出为:

hello:  A type of greeting

我尝试在上面编写的循环中添加另一个父循环while,条件为file.eof(),但随后程序永远不会进入两个子循环。

【问题讨论】:

  • @buildsucceeded 否,因为仅在 读取不成功后才设置 eof。但是在 Frexpe:您是否尝试过使用 Google 或本网站的搜索功能?这个问题被问过很多次了,网上有很多例子
  • 改用while(getline(file,line,'\n')) { desc = line;}
  • 阅读好的 C++ programming book 并查看 this C++ reference,也许还有 C++11 标准 n3337。从现有的 C++ 开源项目(例如 GCCRefPerSysfish...)中获取灵感。阅读他们的文档后使用GCCGDB

标签: c++ file multiline getline


【解决方案1】:

您不需要多个循环,一个循环就足够了。读取一行,然后根据需要使用std::istringstream 将其拆分。对每一行重复。

例如:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

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 (getline(file, line) && (line != ".")) {
        istringstream iss(line);
        iss >> word;
        getline(iss, desc);
        cout << word << ":  " << desc << "\n";
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多