Help sending size of a string into a file

Hey everyone, I cant figure out how to do this, i dont know the name in english for this technique but basically i just get the size of a char, store into an int, then send both int and char to the file. With char is working good, but i cant with string. Here both codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   //Write it
    cout <<endl<< "Name: ";
    cin.getline(nombre,50);
    ofstream Save("file.txt",ios::app);
    dim_name = strlen(name);
    Save.write((char*)&dim_name, sizeof(int));
    Save.write((char*)&name, dim_name);

    Save.close();

    //Print it
    ifstream print("file.txt");
    while(!print.eof()){
       print.read((char*)&dim_nombre, sizeof(int));
       print.read((char*)&name, dim_name);
       name[dim_ame] = '\0';
			
       cout << name << endl;
    }
    print.close();


And this is my failed attempt to do with string, it saves the strings but when i print i get trash and some duplicated strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    cout <<endl<< "Name: ";
    getline(cin >> ws,name);
    ofstream Save("file.txt",ios::app);
    dim_name = name.size();

    Save.write((char*)&dim_name, sizeof(int));
    Save <<nombre;

    Save.close();


    ifstream print("file.txt");
    while(!print.eof()){
         print.read((char*)&dim_name, sizeof(int));
         getline(print,name);

         cout<<name<<" "<<endl<<endl;
    }
    print.close();


thanks in advance.
getline stops at a line break, ¿did you put a line break in your file?
@ne555 no I didn't. The thing is that I dunno how to do what I need, I'm just doing as many things comes to my mind, lol. So, how should i read just the specific size stored into the integer?

@keskiverto, imma check the link provided...
Last edited on
Topic archived. No new replies allowed.