我的结构数组的文件写入函数有问题。我收到错误,could not convert 'cars[n]' from 'car' to 'std::string {aka std::basic_string<char>}'
我对文件写入有点困惑,也许有人可以解释或给我一些提示如何使我的写入功能起作用?
我的代码:
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <fstream>
using namespace std;
#define N_CARS 2
struct car{
string model;
int year;
double price;
bool available;
}cars [N_CARS];
void writeToFile(ofstream &outputFile, string x )
{
outputFile << x << endl;
}
int main ()
{
string mystr;
string mystr2;
string mystr3;
int n;
for (n=0; n<N_CARS; n++)
{
cout << "Enter title: ";
getline (cin,cars[n].model);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> cars[n].year;
cout << "Enter price: ";
getline (cin,mystr2);
stringstream(mystr2) >> cars[n].price;
cout << "Choose availability: ";
getline (cin,mystr3);
stringstream(mystr3) >> cars[n].available;
}
ofstream outputFile;
outputFile.open("bla.txt");
for (n=0; n<N_CARS; n++)
writeToFile(outputFile, cars[n]);
outputFile.close();
system("PAUSE");
return 0;
}
我说得对吗 outputFile << x << endl;
将写入文件我的整个结构字段?
最佳答案
Am I getting it right that outputFile << x << endl; will write to file my whole struct fields?
以下内容:
void writeToFile(ofstream &outputFile, string x )
{
outputFile << x << endl;
}
与您的结构或字段完全无关。它写入一个字符串。
以下内容:
writeToFile(outputFile, cars[n]);
调用一个接受 std::string
的函数, 并尝试传递 car
给它。那是行不通的。
您有多种选择:
使用
<<
自行输出结构的每个成员.重载
<<
运算符为您的结构,以便您实际上可以做outputFile << mycar
, 其中<<
将调用您的重载运算符。 (这是最好的选择。)使您的结构可转换为
std::string
.这会反过来咬你一口,因为在某些时候你将不可避免地需要从流中读取你的结构,然后你将不得不让你的结构也可以从 字符串转换,这意味着字符串解析,这是一项丑陋且容易出错的工作。
关于c++ - 结构数组写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42595848/