c++ - 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?
解决方案
不,这不是编译器错误。您正在遇到操作系统之间的行尾差异。我的魔法球告诉我,如果你跑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
..
推荐阅读
- amazon-web-services - 如何为 VPN 上的 Private Route 53 托管区域获取有效的 SSL 证书
- apache-kafka - 没有输入主题的拓扑将不会创建流线程和全局线程
- c# - 服务器响应中的 DateTime.UtcNow 显示比响应后客户端调用的 DateTime.UtcNow 更晚的时间
- git - 使用本地 Git LFS 存储库检查是否有任何文件更改而无需在 .git 下复制
- python - 多个用户输入和他们的第二个输入
- python - GET 请求的格式
- apache-kafka - Apache Kafka 与 HTTP API
- r - Shiny R中的密度图未按预期工作
- java - java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFRow
- flutter - Flutter 在滚动时将容器保持在顶部