Reading Integers From File

Alright, I am trying to use isdigit() to determine if the input from the ifstream is an integer. However, this is not working the way it should.

My txt file has this:
1
2
3
4
1
2
Hello
3


This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <iomanip>
#include <fstream>
#include <ctype.h>
using namespace std;

int main() {
   int dataIn; int sum = 0; int count = 0;
    ifstream infile;
    infile.open("3.dat", ifstream::in); //INPUT THE FIRST NUMBER
    
    if(!infile){
             cout << "Unalbe to open file";
             system("pause");
             }
    
    while(infile >> dataIn){     //WHAT CONDITION IS NEEDED IN THE WHILE?
              if(isdigit(dataIn)){
                    cout << dataIn << endl;
                    sum = sum + dataIn;
              }else{
                    cout << "You ran into something that is not a digit" << endl;
                    break; 
                    }
              count++;
    }
    infile.close();                    //CLOSE THE STREAM
    cout << "The sum of the numbers is " << sum << endl;
    cout << count << endl;
    system("pause");
    return 0;

}


What should happen is that the file should read until a non-digit is present. Once "Hello" is reached it should throw out that else error and break, but for some reason it skips right to "Hello". As I see it "Hello" is in the third position of that text file. So sum should be 0+1 the first iteration, then 1+2 the second iteration, and counter should be 2 before it gets to a non-digit. Any ideas?
Last edited on
Topic archived. No new replies allowed.