Storing string to a file
How can i store strings to a file?
u see if i have:
string name="McCall";
and i store it to file using ofstream, its just numbers in the file so obviously its kinda difficult to load from the file.
Soo does the string type have any operator perhaps to get chars, not the memory address or what ever it gaved to me?
Include your write/read code. Here that is.
I have spoken.
[edited by - Zorak on December 23, 2002 10:43:15 AM]
I have spoken.
[edited by - Zorak on December 23, 2002 10:43:15 AM]
Here is code that shows both how to read and write strings to a file:
- Andy Oxfeld
#include <stdio.h>int main(){ FILE* fptr; char mystr[] = "Hello World"; char anotherstr[101]; /* Write "Hello World" to file "hi.txt" */ fptr = fopen("hi.txt", "wt"); /* w means write, t means text file */ fprintf(fptr, "%s", mystr); /* Write string mystr */ fclose(fptr); /* Now read that string back in */ fptr = fopen("hi.txt", "rt"); /* r means read */ fscanf(fptr, "%100s", anotherstr); /* Read string in */ fclose(fptr); /* To prove this worked, we''ll print anotherstr to the screen */ printf("The string is: %s\n", anotherstr); return 0;}
- Andy Oxfeld
Unfortunately that uses C style strings, and the OP was using std::string (well ''string'', which is a class anyway)
quote:Original post by Evil Bill
Unfortunately that uses C style strings, and the OP was using std::string (well ''string'', which is a class anyway)
Then it''s about time for the OP to learn to use C style strings
- Andy Oxfeld
True, but still, i thought there was a way to read & write std::strings to a file.
I dunno, i don''t tend to use the STL much.
I dunno, i don''t tend to use the STL much.
You could write a string similarly to my example above but using stringvariablename.c_str() where I used mystr, like this:
To read in a string, you could read it into a character array like I did, and then do:
- Andy Oxfeld
fprintf(fptr, "%s", stringvariablename.c_str());
To read in a string, you could read it into a character array like I did, and then do:
stringvariablename = anotherstr;
- Andy Oxfeld
Uh, what''s wrong with ofstream/ifstream?
This should work (not tested)
This should work (not tested)
#include <fstream>#include <iostream>#include <string>int main() { std::string st = "boo"; { std::ofstream out("test.txt"); out << st; } std::string st2; { std::ifstream in("test.txt"); in >> st2; } std::cout << st2 << std::endl;}
this post was an evil twin of the one above
[edited by - civguy on December 23, 2002 12:31:20 PM]
[edited by - civguy on December 23, 2002 12:31:20 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement