Basic fstream with c++
its been a long time since i have done c++. i need to read in data from a text file. there is one word on each line, and part of what i need to do is to read in each word and store it as a string.
i was looking on the net for getline() and such, and i did this as a small test to see if i could get fstream towork:
but all it does is read the first line over and over. how do i increment the position to the next line?
cout << s << endl;
You don't have to increment anything because the get pointer is at the end of the line--all you have to do is read in another line.
I suspect, however, that you didn't really post all the relevant code, and that the above code is in a loop. If you open the file again, the get pointer is reset to the beginning. You only want to open the file once.
Also, you don't have to read into a char array and then assign it to a string. There's a string function called getline() that you can use to directly read into a string type:
Last edited by 7stud; May 19th, 2003 at 07:58 PM.
hey thanks for the help. you're right, that wasn;t the all the relevant code, there were some function calls to do stuff wtih b+ trees that weren't important. but the weird thing is, i did only open the file once...i dont know. anways i used the getline function you suggested and it worked like a charm. thanks!
btw, what library is that part of?
"ii did only open the file once...i dont know"
Well if you only opened the file once, then you only encounter this line once:
and therefore you are only reading in one line total, but you said in your first post,
"all it does is read the first line over and over"
How is that possible when your program only encounters the line once? If the lines you posted are inside a function, then everytime the function is called, the file is reopened.
"btw, what library is that part of?"
the function was main().
all it did was read in the first line over and over in an infinite loop.
anyways, its not imporant. thanks for ur help.
Last edited by clam61; May 20th, 2003 at 01:15 AM.
June 26th, 2003, 06:57 AM
just try it like this:
cout << s << endl;
that de programm allways printed the first line is normal, because you had the cout in the loop.... but there was no increment....
so nice day and good luck