【发布时间】:2013-03-01 13:10:17
【问题描述】:
我想将用户接受的std::string 变量写入文件。我尝试使用 write() 方法并将其写入文件。但是当我打开文件时,我看到的是框而不是字符串。
字符串只是一个可变长度的单个单词。 std::string 适合这个还是我应该使用字符数组之类的。
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();`
}
【问题讨论】:
-
请出示您的代码。一般来说,如果正确使用,
std::string就可以了。 -
您需要保存字符串的“有效负载”内容,而不是字符串对象本身(通常只包含长度和指向实际内容的指针)
标签: c++