Storing string to a file

Started by
21 comments, last by Craazer 21 years, 3 months ago
quote:Original post by Craazer
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?

Just be more careful when your string consist of empty spaces. Reading is slightly different when there's empty spaces in between your string. IMO, writting-out and reading-in line-by-line is the easiest. See also getline() or fgets().

[EDIT] Oh, your solution has been mentioned above (in C and C++ both version), so I needn't repeat it here.

[edited by - DerekSaw on December 23, 2002 10:33:57 PM]
"after many years of singularity, i'm still searching on the event horizon"
Advertisement
quote:Original post by AndyOxfeld
Here is code that shows both how to read and write strings to a file:
#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

It won't work. You need fgets() and fputs() pair. The output is "Hello" only.

And the cin/cout solution too need special tricks to read string with whitespaces.


[edited by - DerekSaw on December 23, 2002 10:53:59 PM]
"after many years of singularity, i'm still searching on the event horizon"
Ok, thank you for the replies, i think i know how to do it now.
And merry christmas

This topic is closed to new replies.

Advertisement