ifstream输出中的奇怪字符

Weird characters on the output of an ifstream

本文关键字:字符 输出 ifstream      更新时间:2023-10-16
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
int main(){
  char a;
  cout << "give me the filename: ";
  cin >> filename;
  ifstream caroll;
  caroll.open(filename.c_str());
  while (a=caroll.get() && !caroll.eof()){
    cout << a << "    ";
  }
  caroll.close();
}

我得到的输出充满了奇怪的字符。它们就像小方块,里面有2个0和2个1

请打开编译器的警告级别。这里有一个bug:

while (a=caroll.get() && !caroll.eof()) {

这被解释为:

while (a = (caroll.get() && !caroll.eof()) ) {
           ^                             ^

你需要给赋值加上括号:

while ((a = caroll.get()) && !caroll.eof() ) {
       ^                ^

GCC发出警告。

(注意:请提交编译代码,filename没有在您的示例中声明,当您应该包括string时,您包括了cstring)