Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I'm trying to make a relatively simple program but I can't remember what to do to get it to work. What I basically want it to do is read in information from an external file that contains characters and numbers, like (44, 12)\n , of course there's a bunch of them in a row so that's why I put that \n there. I don't care for those characters, I just want to put the first number in a variable and the second number in another. Now, I'm not sure what I'm doing wrong. I've been trying to start off by doing:
ifstream infile;
infile.open("file.txt");
while( infile )
{
infile >> x;
if ( x == '(' )
infile >> x;
...}
Am I using the wrong method? I'm obviously no expert at this yet, I've read many tutorials on file reading but none showed how to exclude non-integers. I want the reader to skip the characters and just continue reading in and store that number in a variable for later calculations. I don't want to use getchar() that would overly complicate things. I've thought about getline() but I don't know how that thing works, does it skip spaces or characters? I don't know. I'm not totally sure what I'm doing wrong, I thought originally what I was doing was right but my program just hangs and does nothing.

Am I using the wrong method?
Probably; it depends on the type of x.my program just hangs and does nothing.
I'm kinda surprised it hangs; the loop should break after the first pass.If x is an int, as I assume it is, then the next bit of text you read better be convertible into an int. Obviously, ( cannot.
What to do about this? Personally, I'd make a function, like this:
int readVal(istream &in) {
int x = 0;
//We move forward, looking for digits...
while (in && (unsigned)(in.peek() - '0') > 9)
in.ignore();
//If in.eof(), this will fail, and we'll return 0;
in >> x;
return x;
}
Then I'd modify your given bit of code to read like this:ifstream infile("file.txt");
//If we got a non-zero value into x, !infile.eof()
//Or, if x = 0, continue to loop if infile.good().
while (x = readVal(infile) || infile) {
. . . .
}

![]() |
sigcheck help
|
excel vba for hyperlinks
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |