C ++ I / O doesn't understand why there is -1

I am just trying to read every character from a file and print it on the screen. For testing, I tried to print the ascii value on the console screen before printing characters.

the contents of the file I'm trying to read is shown below:

assign1_2.cpp:33:20: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)' 

I used the code below

 #include <iostream> #include <fstream> #include <string> #include <vector> #include <stdlib.h> using namespace std; void CountLetters(string filename); int main() { CountLetters("count.txt"); } void CountLetters(string filename) { cout << filename << endl; ifstream in; in.open(filename.c_str(), ios::in); vector<char> letter; char temp; while (!in.eof()) { cout << in.get() << endl; } in.close(); } 

After running this code, and I see "-1" at the end of the console screen. Anyone please explain? thanks

+2
source share
1 answer

Do not read, not eof() 1 . This is not a valid read cycle.

Reading while reading is successful .

 int x; while ((x = in.get()) != EOF) { cout << x << endl; } 

Testing in.eof() does not guarantee that reading will succeed. When you test in.eof() , you are actually checking if previous reads were trying to read the end of the file. This is bad because it means that the previous read operation failed. That failed, and you didn't care, and just clicked to use the return value, even if it didn't work out.

When in.get() fails, it returns an EOF constant. This is what you should check. If in.get() fails, you don't want to continue your loop as if it succeeded.


1 The same applies to while good() or until bad() .

+14
source

All Articles