首页 > 解决方案 > Possible compiler bug while reading file and outputting contents

问题描述

While trying to help a friend with a problem with his code, I encountered a very weird bug when compiling the following code with GCC.

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

int main() {
    std::ifstream classes("classes.txt");
    std::string line;
    std::string txt = ".txt";
    while (std::getline(classes, line)) {
        std::cout << "[-]: " << line << "," << txt << std::endl;
    }
    return 0;
}

classes.txt contains the following:

CSC1
CSC2
CSC46
CSC151
MTH121

When compiled with Clang or MSVC, the output is as follows:

[-]: CSC1,.txt
[-]: CSC2,.txt
[-]: CSC46,.txt
[-]: CSC151,.txt
[-]: MTH121,.txt

But, when compiled with GCC, this is what the code outputs:

,.txtCSC1
,.txtCSC2
,.txtCSC46
,.txtCSC151
[-]: MTH121,.txt

I cannot make sense of whats happening here. Can anyone explain this?

Image with GCC version and output: enter image description here

标签: c++gcc

解决方案


不,这不是编译器错误。您正在遇到操作系统之间的行尾差异。我的魔法球告诉我,如果你跑dos2unix classes.txt,问题就会消失。同样,cat -v classes.txt应该输出类似于以下内容:

CSC1^M
CSC2^M
CSC46^M
CSC151^M
MTH121^M

在这里,^M表示\r\n。这称为 CRLF 或“回车换行”。在 Linux 上,当遇到回车时,它会指示终端返回到行首。这会导致.txt覆盖您之前输出的任何内容。

注意,如果您在 Apple 系统上运行 Clang,我猜您是,某些版本的 Mac 使用\r,但不是\r\n\n..


推荐阅读