-
file i/o
Hi everyone :)
Hopefully u can help me with this problem. pleaseee help :)
How do you make my code read one line after another. Right now my code is only reading the first line, I want it to read the first and any other lines that may exist in the file.
----------FILE THAT CODE IS READING FROM-------
Name 3857
Name2 454959268
Name 3 32895 342
----------------------------------------------------------
#include <fstream.h>
#include <iostream.h>
int main()
{
char name[10];
fstream a_file("Names.dat", ios::in);
a_file>>name;
cout<<name;
a_file.close();
}
Many thanks in advance :) :) :)
-
If what you did reads one line at a time, you could loop it to read several lines. I'm not so used with c++ way of reading from files, I have only bad memories from that :). Rememeber to check for end-of-file before you read too (eof()).
This might work, however I haven't tested it:
Code:
while(!a_file.eof())
{
a_file>>name;
cout<<name;
}
-
//attempt to read in first line (can't have any spaces in line!!)
a_file >> name;
while(a_file)
{
//display name
cout<<name;
//then read in next name
a_file>>name;
}
the line:
while(a_file)
as long as the stream is valid. If you read in EOF then the stream is no longer valid so the loop stops. There are other reasons why the stream may become invalid too.
this syntax would be found in many programs:
while(a_file >> name)
cout << name;
can't say as there is anything wrong with it either.
here's another workable version:
a_file >> name;
while(!a_file.eof())
{
cout << name;
a_file >> name;
}
and there are more styles as well. You can choose based on personal preference or particular needs of the program.
-
if lines have spaces or other whitespace in them then use getline:
a_file.getline(name, 10)
instead of
a_file >> name;
However, name may need to be longer than 10 if you are planning to get all the digits into the same buffer as the letters.
You need to be very clear what the file is like and what information you want to be stored where.
-
The book I was reading was confusing so here's a question. When you read in info from a file, is the pointer to the location of the cursor is automatically moved forward to the next word? Does it automatically go to the next line as well?
-
have exactly the same question :)