Weird characters on the output of an ifstream
#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();
}
I am getting output full of weird chars. They are like little squares filled with 2 0's and 2 1's.
Please turn on your compilers warning level. There's a bug here:
while (a=caroll.get() && !caroll.eof()) {
This is interpreted as:
while (a = (caroll.get() && !caroll.eof()) ) {
^ ^
You need to add parenthesis around the assignment:
while ((a = caroll.get()) && !caroll.eof() ) {
^ ^
GCC warns about this.
(Note: please post code that compiles, filename
is not declared in your sample, and you're including cstring
when you should be including string
.)
精彩评论