【问题标题】:Problem with combining lines form file with custom text in cout [closed]将行表单文件与 cout 中的自定义文本组合的问题[关闭]
【发布时间】:2019-12-10 20:45:50
【问题描述】:

我在将 getline 中的字符串与 cout 中的其他字符串组合时遇到问题,我一直在寻找答案,但找不到任何有类似问题的人。我的代码是:

file.open ("list.txt");
    getline(file, line);
    int i=0;
    do
    {
        getline(file, line);
        dummyStudent.name = line;
        cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
        students.push_back(dummyStudent);
        i++;
    }
    while(!file.eof());
    file.close();

输出应该是:

Is student present?

但是我得到了:

 present?udent

循环的最后一次迭代显示正确的文本。

【问题讨论】:

  • 我相信这是你的问题 - stackoverflow.com/questions/2129230/…
  • @Kai 看起来不像。 cout 语句中的所有内容都是相互独立的,因此这里不应该有 UB,因为这里有序列点。
  • 可能是因为除了最后一行之外的每一行末尾都有回车符 (\r)?
  • 你能检查getline的结果,看看是不是false

标签: c++ c++11 visual-c++ c++14


【解决方案1】:

让我在这里猜测一下。您的文件是在 Windows 上创建或编辑的,但您没有使用 Windows 来构建/运行您的代码。因此,每行末尾的换行符 (\n) 都不是换行符,而是换行符 回车符:\r\n。然而,文件的最后一行没有换行符(因此没有回车)——所以只有那个看起来不错。我说的对吗?

回车会将光标返回到行首。因此,您读入student\r,然后std::cout 写入Is student,看到回车并将光标移回行首并在那里写入present?。导致present?udent

name 字符串的末尾去掉空格(借助https://stackoverflow.com/a/217605/2602718 的代码)

static inline void rtrim(std::string &s) {
    s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

int main() {
    //...
    getline(file, line);
    dummyStudent.name = line;
    rtrim(dummyStudent.name);
    cout << "Is " << flush << dummyStudent.name << flush << " present?" << endl;
    //...

或者从您的文件中删除这些字符。 (听说您使用的是 MacOS 后,您可以使用以下内容从文件中删除这些字符:Removing Carriage return on Mac OS X using sed

【讨论】:

  • 在以文本模式打开文件的 Windows 上应该不是问题。应该只在二进制模式下或者在其他平台读取windows文件有问题
  • 我想我只是假设他们在 Linux @Alan 上。我已经编辑明确假设它们不是在 Windows 上构建/运行。好收获!
  • 这个问题被标记为visual-c++,所以我假设它们在windows上。杂散的回车绝对是问题
  • 我的文件是在 windows 上编辑的,但我在 mac 上
  • @Bruno 在这种情况下,我会考虑在您的文件上运行类似的内容:stackoverflow.com/q/21621722/2602718
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 2013-05-29
  • 1970-01-01
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多