结构数组写入文本文件

Structure array writing to text file

我的结构数组的文件写入功能有问题。我收到错误,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。这会反过来咬你一口,因为在某些时候你将不可避免地需要从流中读取你的结构,然后你将不得不让你的结构也可以转换 from string,表示字符串解析,是丑陋且容易出错的事情