0

I have the following code:

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

int main()
{
    string file;
    cout << "Please enter input file name: ";
    cin >> file;

    int count[128] = {0};

    ifstream in(file.c_str());

    char one;
    cin >> noskipws;

    while(!in.eof()){
        in.get(one);
        count[static_cast<int>(one)]++;

        cout << one << " : " << static_cast<int>(one) << endl;
    }
}

For an input file of:

Hello.
Line 2

My program tells me that there are two 2's at the end of the file. Why is this? To be clear, this is what I output:

H : 72
e : 101
l : 108
l : 108
o : 111
. : 46

 : 10
L : 76
i : 105
n : 110
e : 101
  : 32
2 : 50
2 : 50

Which is what I want besides for the two 2's at the end.

user3340001
  • 217
  • 1
  • 4
  • 8

1 Answers1

1

The code should be like this

while(in.get(one)){
       count[static_cast<int>(one)]++;
       cout << one << " : " << static_cast<int>(one) << endl;
}

It should resolve your problem with doubling end number.

Ardel
  • 315
  • 2
  • 9
  • duplicating the input code to work around the erroneous use of `.eof()` gets pretty ugly if the input code is more than a simple `.get()`. Besides, this is still failing to check if the first `.get()` failed. – Cubbi Mar 04 '14 at 20:32
  • Yes, you're right (Cubbi), I hope I fixed the problems you mentioned. – Ardel Mar 04 '14 at 21:08
  • just one more step to the normal C++ input loop `while(in.get(one))` – Cubbi Mar 04 '14 at 21:10
  • Ok, I surrender. Can you tell me how this loop will end and why. Because a can't understand how returning EOF from .get() will end it. – Ardel Mar 04 '14 at 21:31
  • the duplicate question's [accepted answer](http://stackoverflow.com/a/5605159/273767) has an explanation – Cubbi Mar 04 '14 at 21:34