I want to read from a simple text file to a string, I thought I had it covered - but for some reason I cannot get it to work. I searched the archives, adn to my amazement an old example looks pretty much identical to mine, the archived example looks as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
void main ()
{
string STRING;
ifstream infile;
infile.open ("names.txt");
while(!infile.eof) // To get you all the lines.
{
getline(infile,STRING); // Saves the line in STRING.
cout<<STRING; // Prints our STRING.
}
infile.close();
system ("pause");
}
string inlasning ()
{
string text;
ifstream file;
file.open ("test_text.txt");
while (!file.eof())
{
getline (file, text);
}
cout << "THE FILE, FOR TESTING:\n" // For testing
<< text << "\n";
file.close();
return text;
}
What happens is - nothing! I don't even get a text back from the cout testing lines I have implemented. And here's the fun part; it WORKS if I have only one line in the textfile I am reading from.
For the life of me I cannot figure this out, and would appreciate input.
In the while loop, "text" is always replaced by a new line in the file, so in the end, it only contains the last line in the file, as getline() does not append to the end of the string, but replaces the previous content. That example worked since the input from the file was immidiately outputed to cout, before STRING was being replaced with the new line.
If you want to make a long string which contains all the newline characters, etc. you could use a temp string which gets the line from the file, and the append() function to append the temp string to a main string.
It's likely that you're looking in the wrong directory for the file. It has to be in the current directory, but if you're running your program from an IDE, it's not always clear what directory that is.
In the while loop, "text" is always replaced by a new line in the file, so in the end, it only contains the last line in the file, as getline() does not append to the end of the string, but replaces the previous content. That example worked since the input from the file was immidiately outputed to cout, before STRING was being replaced with the new line.
If you want to make a long string which contains all the newline characters, etc. you could use a temp string which gets the line from the file, and the append() function to append the temp string to a main string.
Ramses, thank you. I did not know that getline() replaced the previous content. That explains the mystery.
kbw, thanks, but the problem is not that the file is not located in the same directory.
Now, I have to figure out a way to append - I'll give it a shot. Thank you for your replies.