-
Reading from txt
how can you make a string equal to a stream from a txt file?
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
string yay;
ofstream a ("yay.txt");
a<<"stringystring!";
istream at ("yay.txt");
yay=getline(a, line);
}
my code is somewhat like the above
-
Code:
string MyString;
ifstream in ("whatever.txt");
getline( in, MyString );
cout<< MyString;
There's no error checking here. I'd recommend a
if ( in ) //
or something similar
-
>how can you make a string equal to a stream from a txt file?
I'm not sure I understand what you want. Do you want to fill a string with the entire contents of a file? If so, this should work for you:
Code:
#include <fstream>
#include <iostream>
#include <sstream>
int main()
{
std::ifstream in ( "test.txt" );
if ( in ) {
std::stringstream ss;
ss<< in.rdbuf();
std::cout<< ss.str();
}
}
-
Note that the str() function in that code returns the string that you can store in a variable if you'd like. The last time I recommended this strategy I failed to point that out and it led to some confusion.
-
The point is to store a name in a txt file, and retrieve it later, even if there are other things in the file
-
Then your code is on the right track. Go ahead and try it (and fix the little mistakes) and see if it works.
One thing to watch for is if you output the string to the ofstream, you should probably close that ofstream before opening the file and reading the string with the ifstream. Also, you may want to consider adding a newline to the end of the string if you really are going to output only that to the file.