如何将std::string写入文件
How to write std::string to file?
我想写一个我从用户接受的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();`
}
您当前正在将string
-对象中的二进制数据写入文件。这个二进制数据可能只包含一个指向实际数据的指针和一个表示字符串长度的整数。
如果你想写一个文本文件,最好的方法可能是使用ofstream
,一个"out-file-stream"。它的行为与std::cout
完全相同,但输出被写入文件。
下面的示例从stdin中读取一个字符串,然后将该字符串写入文件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;
}
请注意,out.close()
在这里并不是严格必要的:只要out
超出作用域,ofstream
的解构器就可以为我们处理这个问题。
有关更多信息,请参阅c++参考:http://cplusplus.com/reference/fstream/ofstream/ofstream/
现在,如果您需要以二进制形式写入文件,您应该使用字符串中的实际数据来执行此操作。获取此数据的最简单方法是使用string::c_str()
。所以你可以使用:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
假设您正在使用std::ofstream
写入到文件,下面的代码片段将以人类可读的形式写入std::string
到文件:
std::ofstream file("filename");
std::string my_string = "Hello text in filen";
file << my_string;
将ios::binary
从你的ofstream模式中移除,并在你的write.write()
中使用studentPassword.c_str()
而不是(char *)&studentPassword
如果您有fmt可用:
#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{} {}", ch, studentPassword);
// ...
但是你不是真的在给文件写密码,对吧?
- 'string'文件在带有C++文件的iOS插件上找不到
- C++将文件行分离为String和Int
- pip install uwsgi 失败,出现 /usr/local/include/string/string.h:7:10:致命错误:找不到'sstream'文件?
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 无法将文件的内容读入 std::string
- 如何使用 rapidjson 读取 json 文件并输出到 std::string?
- Qt UTF-8 文件到 std::string 添加额外的字符
- 将C 数组写成文件,避免创建std :: String
- 我是否也应该包括 string.h,即使它存在于头文件中
- 如何使用矢量数据使用 rapidjson 库创建 json 文件<string>?
- 使用 std::find 查找从二进制文件中读取的字符并转换为 std::vector 中的 std::string<string> 会产生这种不可预测的行为?
- YAML::LoadFile(std::string const&) 找不到文件 [ROS 中的 yaml-cpp]
- 通过读取文件创建映射<字符串,矢量>时如何管理内存<string>
- 将文件的二进制内容推送到 std::string 以用于 Google 的 Snappy
- 如何在C 中的文件中直接读取std :: String中的字符串
- 比较输入的C弦与文件读取c-string
- 使用 string::find 来解析文件
- 使用 std::write 和 std::read C++ 读取包含 std::string 到.dat文件的结构
- 如何为使用矢量的函数编写 SWIG 接口文件<string>?
- 包括标准头文件.string.h还是cstring?或两者兼有