c++ - 以列表格式读取文件时如何忽略换行符

标签 c++ newline ifstream

我正在尝试读取一个包含标题和作者列表的文件,我需要能够忽略文件中分隔每一行的换行符。

例如,我的 .txt 文件可能有这样一个列表:

The Selfish Gene
Richard Dawkins
A Brave New World
Aldous Huxley
The Sun Also Rises
Ernest Hemingway

我必须使用并行数组来存储这些信息,然后才能像这样格式化数据:

The Selfish Gene (Richard Dawkins)

我试图使用 getline 来读取数据,但是当我去格式化标题和作者时,我得到了这个:

The Selfish Gene
(Richard Dawkins
)

如何在从文件中读取列表时忽略换行符?

这是我目前所拥有的:

    int loadData(string pathname)
    {
    string bookTitle[100];
    string bookAuthor[100];
    ifstream inFile;
    int count = -1; //count number of books
    int i; //for variable

    inFile.open(pathname.c_str());
    {
        for (i = 0; i < 100; i++) 
        {
            if(inFile)
            {
                getline(inFile, bookTitle[i]);
                getline(inFile, bookAuthor[i]);
                count++;
            }
        }
        inFile.close();
        return count;
    }

编辑:

这是我的输出函数:

    void showall(int count)
    {
        int j; //access array up until the amount of books
        for(j = 0; j < count; j++)
        {
             cout << bookTitle[j] << " (" << bookAuthor[j] << ")";
             cout << endl;
        }    
    } 

我是不是做错了什么?

最佳答案

正如@Potatoswatter 所说,std::getline通常会去除换行符。如果换行符仍然通过,您可能正在使用使用 \n 的系统因为它是换行符,但你的文件有 \r\n换行符。

只需将多余的换行符添加到字符串中即可。你可以用类似的东西来做到这一点:

s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::isspace)).base(), s.end());

或类似的。你会发现 std::find_if<algorithm> , std::isspace<clocale> , 和 std::not1<functional> .

关于c++ - 以列表格式读取文件时如何忽略换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963247/

相关文章:

c++ - WinDbg 说在图像列表中找不到 ".dll"

c++ -/Zc :wchar_t- mean? 中的减号是什么

javascript - JS - 如何从 for 循环内的新行开始?

line - mediawiki:如何防止在模板中呈现新行或换行符?

C++ 3D 模型 io、二进制文件读取 (badbit) 和 #DEN 问题

c++ - VS Express 2015 Win10 应用程序 - ifstream 无法打开文件

C++ map 定义基础

java - 文件写入器中现有多行字符串的新行

C++ ifstream 错误检查

c++ - 带有 lambda 函数的 ptr_fun