124

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.

The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.

ofstream write;
std::string studentName, roll, studentPassword, filename;


public:

void studentRegister()
{
    cout<<"Enter roll number"<<endl;
    cin>>roll;
    cout<<"Enter your name"<<endl;
    cin>>studentName;
    cout<<"Enter password"<<endl;
    cin>>studentPassword;


    filename = roll + ".txt";
    write.open(filename.c_str(), ios::out | ios::binary);

    write.put(ch);
    write.seekp(3, ios::beg);

    write.write((char *)&studentPassword, sizeof(std::string));
    write.close();`
}
2
  • 3
    Please show your code. In general, if correctly used, std::string is fine for this. Commented Mar 13, 2013 at 14:27
  • 3
    You need to save the 'payload' CONTENT of the string, not the string object as such (which typically contains just a length and a pointer to the actual content) Commented Mar 13, 2013 at 14:28

4 Answers 4

178

You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.

If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.

The following example reads one string from stdin, and then writes this string to the file output.txt.

#include <fstream>
#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.

For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/

Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:

write.write(studentPassword.c_str(), studentPassword.size());
Sign up to request clarification or add additional context in comments.

5 Comments

I had to add std::ios::binary for this to not have problems with newline characters
out.close() ? twice? bad answer
@caoanan it's to demonstrate the API. I also mention in the text of the body that it happens automatically when the variable goes out of scope. At any rate, close() is idempotent, so there's no harm in it being called multiple times.
In the last example, is it right to multiply sizeof(char)? Does it work even if the sizeof(char) is not 1? I'm asking this because ofstream::write accepts count(number of characters to write), not the number of bytes to write.
@starriet Actually, sizeof(char) == 1 by definition. I removed sizeof(char) from the example since it's unnecessary and confusing.
36

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

Comments

0

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

Comments

0

If you have fmt available:

#include <fmt/os.h>
// ...
    fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...

But you are not really writing a password to a file, right?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.