【问题标题】:How to ignore newline characters when reading file in list format以列表格式读取文件时如何忽略换行符
【发布时间】:2011-08-05 22:25:01
【问题描述】:

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

例如,我的 .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;
        }    
    } 

我在这里做错了吗?

【问题讨论】:

  • getline 应该去掉换行符。也许您在 UNIX 机器上使用了 DOS 文件,而回车符正在滑过并被解释为换行符?
  • 如果对std::getline 的调用失败,则此代码的行为会很糟糕。仅供参考。
  • 你的输出代码是什么样的?
  • 感谢您的回复。我将输出代码添加到问题的正文中。我正在使用 Mac,使用 Xcode 进行编译。那会有什么不同吗?

标签: c++ newline ifstream


【解决方案1】:

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

只需将多余的换行符添加到字符串中即可。你可以这样做:

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

或类似的。您会在&lt;algorithm&gt; 中找到std::find_if,在&lt;clocale&gt; 中找到std::isspace,在&lt;functional&gt; 中找到std::not1

【讨论】:

    【解决方案2】:

    我明白了!问题是我正在阅读的文件。我从导师给我们的 .txt 文件中复制并粘贴了标题和作者的文件,并将其粘贴到一个新的 .txt 文件中,现在它可以正常工作了!谢谢大家的帮助!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 2013-04-07
      • 2011-10-04
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      相关资源
      最近更新 更多