c++ Reading doubles from file, but recording if program encounters a string

StackOverflow https://stackoverflow.com/questions/21667092

  •  09-10-2022
  •  | 
  •  

Domanda

Ok, so my code all works fine but there's a small problem, I have an input file that I want to read from and sometimes a number is replaced by a letter. The file might look like this:

3.5
45.8
gh
67.34
39.5
sj
4.73

I want to know that there were two numbers missing after I'd read in all the values. At the moment my code just ignores them as if they weren't there. I tried this:

double line;
int i = 0;
int j = 0;
while (myfile >> line) {
    if (myfile.fail()) {
        cout << "Error, line is not a number." << endl;
        j = j + 1;
    }
    mydata[i] = line;
    i = i + 1;
}

but the code doesn't ever print the error message! Why not? Thank you. (i counts the numbers, j is supposed to count the errors)

È stato utile?

Soluzione

while (myfile >> line) 
{
    if (myfile.fail()) 
    {
        cout << "Error, line is not a number." << endl;
        j = j + 1;
    }
    mydata[i] = line;
    i = i + 1;
}

Your problem is that the first line while (myfile >> line) will evaluate to false when it gets to the line gh, so your conditional gets skipped altogether. If you are looking to count errors, your code would need to be more like

std::string sLine;
while (std::getline(myfile, sLine)) 
{
    std::istringstream iss(sLine);
    if (!(iss >> line))
    {
        cout << "Error, line is not a number." << endl;
        ++j;
    }
    else
    {
        mydata[i] = line;
        ++i;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top