Now that I look at this, I think you should look away in disgust. I am also pretty new to C++ and I just wanted to give you a quick answer.
Do not use atoi if you can avoid it. It isn't even C++ and your professor will not be impressed. My professors wouldn't even grade me if I used it. I took a little time and wrote a much better algorithm for reseting the stream if it fails.
By now , you know that trying to read in an non-integer data into an integer will cause the stream to the fail. If it is a decimal for instance, it will read until it hits the . and the stream will fail. If you try to read in 23dhfbg it will read until it hits the d and the stream will fail.
Well, you can use this to your advantage. Check out this simple (sorta simple) algorithm I just came up with. It will read in any integers, as long as they are at the beginning of the word. So 23hdgd will be read in as 23, 23.25 will be read in as 23, but dhdh23 will be ignored.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
char buff;
int tmp;
ifstream fin;
fin.open("filename-here");
fin >> tmp;
while (!fin.eof()) {
if (fin.fail()) {
fin.clear();
buff = fin.get();
while (buff != ' ' and buff != '\n')
buff = fin.get();
}
else
// store the integer or reverse the if statement to "if (!fin.fail()) - store the data"
// and store only 100% valid data (Probably a good idea)
fin >> tmp;
}
|
Now if you play around with this you can tweak it to ignore ANY data that causes the stream to fail if you so choose. Using this algorithm will allow you to avoid converting chars or strings to integers which is never 100% guaranteed, or so I have read.