Issue
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in("input.txt");
int i = 0,sum=0;
char x;
while (!in.eof()){
in >> i;
if (in.good()) {
cout << "integer is " << i << endl; sum += i;
}
if (in.fail()) {
in.clear();
in >> x;
cout << "the char is " << x << endl;
}
}
cout << sum;
char z;
cin >> z;
}
and my input.txt is like:
bear: sdf 23 okI am fine 11q , 45
and my screen output is like:
the last number 45 doesn't show up
So what happened here? why 45 is regarded as one out of file. And if I add a 's' immediately right next to 45, the screen will have two s showing up, rather than just one.
Solution
The problem is that when extracting symbols for 45,it tries to extract symbol after '5' (to check if number continues further) and sees end of file, setting eofbit
. This makes in.good()
test to fail. Suggestions:
while (!in.eof()){
in >> i;
if ( in ) { //Not .good(), just conversion to bool
Or
while (!in.eof()){
if ( in >> i; ) { //both extraction and checking in same operation
Remember, .good()
is not the same as checking stream state. .good()
is telling if stream ready for further input. Bool conversion does ! .fail()
and checks if last operation was executed succesfully
Answered By - Revolver_Ocelot Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.