当我运行下面的代码时,我的期望是打印以屏幕形式显示“文件字符是”的文本,然后是文件中的字符,然后是用\\字符分隔的字符。
#include <fstream>
#include <filesystem>
using namespace std;
int main() {
ifstream in;
string filename = "binFile.txt";
int size = std::filesystem::file_size(filename);
in.open(filename, ios::in | ios::binary);
cout << "file characters are" << flush;
// cout << "file characters are" << endl; this works as expected
char ch;
for (int i = 0; i < size; i++) {
in.read(&ch, sizeof(char));
cout << ch << "|";
}
}但是,由于某些原因,字符串“文件字符是”没有正确显示,相反,“文件字符是”中的“f”被“\\”替换,即
|ile characters are1|2|....
...Remaining text.....我尝试在我的cout命令中使用endl,但是它仍然不起作用,但是在cout的末尾使用endl是有效的。有人能告诉我为什么cout会有这种奇怪的行为吗?
发布于 2021-10-04 15:19:10
以下几点对我来说很好:
g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.cat file_characters.cpp
#include <iostream>
#include<fstream>
#include <filesystem>
namespace fs = std::filesystem;
using namespace std;
int main(int argc, char**argv) {
ifstream in;
string filename = string(argv[1]);
int size=fs::file_size(filename);
in.open(filename, ios::in | ios::binary);
cout << "file characters are"<<flush;
//cout << "file characters are"<<endl; this works as expected
char ch;
for (int i = 0; i < size; i++) {
in.read(&ch, sizeof(char));
cout << ch << "|";
}
return 0;
}g++ -std=c++17 file_characters.cpp a.out a.out | tr '\014' '\012' | head -1
file characters are|E|L|F|||||||||||||||>||||||�|$|||||||@||||||||X|y|||||||||||||@|| ||||||||||||@||||||||@||||||||@||||||||�||||||||�|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||�||||||||�||||||||||||||||||||||||| |||||||| |||||||| |||||||U||||||||U|||||||||||||||||||||||||@||||||||@||||||||@|||||||||||||||||||||||||||||||||||||`|L|||||||`|\|||||||`|\|||||||�||||||||�||||||||||||||||||||||||x|L|||||||x|\|||||||x|\||||||||||||||||||||||||||||||||||||||8||||||||8||||||||8|||||||| |||||||| ||||||||||||||||||||||X||||||||X||||||||X||||||||D||||||||D||||||||||||||||S|�|t|d|||||8||||||||8||||||||8|||||||| |||||||| |||||||||||||||P|�|t|d|||||T|@|||||||T|@|||||||T|@|||||||d||||||||d||||||||||||||||Q|�|t|d|||||||||||||||||||||||||||||||||||||||||||||||||||||R|�|t|d|||||`|L|||||||`|\|||||||`|\|||||||�||||||||�||||||||||||||||/|l|i|b|6|4|/|l|d|-|l|i|n|u|x|-|x|8|6|-|6|4|.|s|o|.|2||||||||||||||||||G|N|U|||||�|||||||||||||||||||||||||G|N|U||�|h|�|�||�|�|8||�|�|�|�|�||>|t|#|| |||||||||||||G|N|U||||||||||||||||||||||||||-||||||||||||||�|||| ||-||||||||.||||�|e|�|m|4|�|=|�||�|https://stackoverflow.com/questions/69437207
复制相似问题