0

I am reading in from an input file "numberSequence.txt", data in it is "6 7 1 9 7 8 0 9 9 5 0 6 7 6 4 5 1 2 2 8" (with blanks)

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream inFile;
    inFile.open("numberSequence.txt");

    int file_input;

    while(!inFile.eof())
    {
        inFile >> file_input;

        std::cout << file_input << " ";
    }

    inFile.close();

    return 0;
}

output i get from this is "6 7 1 9 7 8 0 9 9 5 0 6 7 6 4 5 1 2 2 8", nothing wrong here. But when i change file_input 's type to char

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream inFile;
    inFile.open("numberSequence.txt");

    char file_input;

    while(!inFile.eof())
    {
        inFile >> file_input;

        std::cout << file_input << " ";
    }

    inFile.close();

    return 0;
}

The output becomes "6 7 1 9 7 8 0 9 9 5 0 6 7 6 4 5 1 2 2 8 8" (last character is printed out twice), why is this the case in char and not in int ?

omni
  • 1
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case, that means changing `std::ifstream inFile; inFile.open("numberSequence.txt");` to `std::ifstream inFile("numberSequence.txt");`. And you don't need to call `inFile.close();`. The destructor will do that. – Pete Becker Sep 16 '21 at 16:36

0 Answers0