我定义了一个goods类型,然后里面有一个string类型的数据,我用文件操作读入赋值给它打印不出来,打印出来也是乱码
参考GPT和自己的思路:
从你提供的截图来看,问题可能出在读取文件的方式上。可以尝试使用 fread 或 fgets 函数读取文件内容,并且要注意文件编码格式和读取时使用的字符集是否一致。在赋值给 struct 中的 string 类型成员变量时,可以使用赋值运算符“=”直接赋值,也可以使用 strcpy 函数进行赋值。示例代码如下:
// 定义 struct 类型
struct Goods {
std::string name;
float price;
// 省略其他成员变量
};
// 定义读取文件的函数
std::string readFile(const char* filename) {
std::ifstream ifs(filename);
if (!ifs) {
return "";
}
std::stringstream buffer;
buffer << ifs.rdbuf();
return buffer.str();
}
// 初始化 struct 类型变量
Goods good;
std::string content = readFile("file.txt");
good.name = content;
// 或者使用 strcpy 函数
Goods good;
std::string content = readFile("file.txt");
char* name = new char[content.size() + 1];
strcpy(name, content.c_str());
good.name = name;
delete[] name;