chompbits
chompbits

Reputation: 341

Checking data types in C++ using ifstream

I'm trying to learn how to upload and read files using ifstream in C++ (fairly new to programming so I'm trying to start simple). As my example file, I have this in a text file:

3
1
2

and this in the main file:

int num;
ifstream infile;
infile.open(filename,ios::in);
infile>>num;
cout<<num<<endl;

so if I replace the first line in my text file:

k
1
2

I want my program to check that the first entry in my file is of type int and then exit out and give me an error if it is not. Instead, I always get 0 as the output. What can I do check for this possible error?

Upvotes: 2

Views: 1567

Answers (1)

David G
David G

Reputation: 96810

This is how it should be done. Checking good() is not recommended:

while (infile >> num)
{
    std::cout << num << std::endl;
}

if (infile.fail() && !infile.eof())
{
    std::cout << "Invalid number";
}

Upvotes: 1

Related Questions