简体   繁体   中英

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

I am simply trying to read each character from a file and print them in the screen. For testing, I tried to print ascii value in a console screen first before printing characters.

the content of the file I am trying to read is 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 these code and I see "-1" at the end in the console screen. Anyone please explain? thanks

Do not read while not eof() 1 . That's not a proper reading loop.

Read while reading succeeds .

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

Testing for in.eof() will not guarantee reading will succeed. When you test for in.eof() you're actually testing if the previous read operation tried to read past the end of the file . This is bad, because it means the previous read operation failed . It failed and you didn't care, and just pressed on to use the value it returned even though it failed .

When in.get() fails, it returns the constant EOF . That's what you should be checking. If in.get() fails, you don't want to continue with your loop as if it succeeded.


1 Same goes for while good() or while not bad() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM