PDA

View Full Version : Yet another C++ Question...


GabrielBlumenthal
12-13-2002, 10:15 PM
Ok, let's say I have a .txt file (or some other random extension name that can hold text). Let's say it just has one number on each line like this:
1
2
3
4
5
How can I read this data into a C++ program, one line at a time?

[This message has been edited by GabrielBlumenthal (edited December 13, 2002).]

Gamma_Ray54
12-13-2002, 10:35 PM
[edit again]...On second thought, I guess it'd be easier to do the C++ way, as opposed to the C way. First, include <fstream.h>. Then, to set up the file, you just say something like:

ifstream thefile("filename.txt");

or whatever you want to call it.

Now, thefile works just like cin. So you can extract variables from it just like cin, by going

thefile >> variable;

As you'll be wanting to put this in a while loop (so you can read as many values as are present), you'll need a way to break out of the loop. If you call thefile.eof(), it will return 1 if you're at the end of the file, and 0 if you're not. So you can use that to control your while loop.

Hope that helps.



[This message has been edited by Gamma_Ray54 (edited December 13, 2002).]

dalf
12-13-2002, 11:41 PM
#include <iostream.h>
#include <fstream.h>

void main(void)
{
int nNums[4],i;
ifstream inf("nums.txt");

i=0;
while (!inf)
{
inf>>nNums[i];
i++;
}
}


It goes something like that. I never liked using fstream.h. I always had a preference to the good ole' C-style fscanf, fprintf, etc.

------------------
"A wizard is never late, Frodo Baggins. Nor is he early. He arrives pricisely when he means to!" --Gandalf

GabrielBlumenthal
12-14-2002, 08:48 AM
Is there anyway to only read one line and assign its value to some variable in the program?

Aaron
12-14-2002, 10:10 AM
I always perfered: fscanf(f,"%i\n",&iVarable); to do that.

Gamma_Ray54
12-14-2002, 11:36 AM
That's what the thefile >> variable; (in mine) and the inf>>nNums[i] (in Gandalf's) lines do. They read one integer from the file and assign it to the specified variable.

Gandalf--I wasn't aware you could evaluate an ios object directly like you're doing in the while loop. Does that automatically call the eof() function, or how does it work?

Actually I prefer the C way too, I just thought this might be a little easier to explain.

[This message has been edited by Gamma_Ray54 (edited December 14, 2002).]

dalf
12-14-2002, 04:21 PM
Yeah, I believe you can just have (!inf) as the condition. Or if I'm wrong you can do
"while (!inf.eof)" as well.

------------------
"A wizard is never late, Frodo Baggins. Nor is he early. He arrives pricisely when he means to!" --Gandalf