【问题标题】:When reading a file through "getline", "\n" is written to the resulting character通过“getline”读取文件时,将“\n”写入结果字符
【发布时间】:2021-03-22 00:38:15
【问题描述】:

通过getline 读取文件时,\n 会写入结果字符。 文件中的数据是这样写的(本例中_代表空格):

2_
c_3_
a_1_

文件中的第一个数字是记录数。

代码:

getline(autorisationFile, temp, ' ');

while (getline(autorisationFile, temp, ' ')) {
        arr[i].login = temp;
        getline(autorisationFile, temp, ' ');
        arr[i].password = temp;
        i++;
    }

【问题讨论】:

  • 你读过std::getline的文档吗?它提取直到“下一个可用的输入字符是delim,正如Traits::eq(c, delim) 测试的那样,在这种情况下,分隔符是从输入中提取的,但不会附加到str”中你的情况delim' ',而不是'\n',所以'\n' 被提取,并附加到str。相关阅读(可能重复):stackoverflow.com/questions/37957080/…
  • 也许,考虑嵌套循环,其中外循环读取一行并将std::istringstream 用于内循环。顺便提一句。 std::getline()' ' 作为分隔符...格式化输入运算符 (>>) 默认使用空格作为分隔符(顺便说一句。² 空格覆盖空格以及 '\n')。所以,std::getline() 在这种情况下可能被过度设计了。
  • 您能否更明确地说明您的问题?我猜你想知道如何在没有\n 的情况下填写password 字段?

标签: c++ file getline


【解决方案1】:

您可能想稍微改变一下解析文件的方式...
如果您逐行处理它,首先使用getline,然后让<< 分割有空格的行。

while (std::getline(authorisationFile, temp)){
        std::istringstream line(temp);
        line >> arr[i].login;
        line >> arr[i].password;
        i++;
    }

Playground with proof of work(编辑了一些初始代码以解决缺失的部分;))

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 2016-01-13
    • 1970-01-01
    • 2013-02-28
    • 2012-05-16
    • 1970-01-01
    • 2016-09-04
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多