结构数组写入文本文件

Structure array writing to text file

本文关键字:文本 文件 数组 结构      更新时间:2023-10-16

我的结构数组中的文件写入功能有问题。我遇到错误, 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;会写入我的整个结构字段吗?

是否正确

我是正确的,那是outputfile&lt;&lt;x&lt;&lt;端写信会提交我的整个结构字段吗?

以下内容:

void writeToFile(ofstream &outputFile, string x )
{
    outputFile << x << endl;
}

与您的结构或领域无关。它写一个字符串。

以下内容:

writeToFile(outputFile, cars[n]);

调用接受std::string的函数,并尝试将car传递给它。那是行不通的。

您有许多选项:

  • 使用<<

  • 为您的结构重载<<操作员,以便您可以实际进行outputFile << mycar,其中<<将调用您的过载操作员。(这是最好的选择。)

  • 使您的结构可转换为std::string。这将转过身来,稍后再咬您,因为在某个时候,您不可避免地需要从流中读取您的结构,然后您将必须从 string的结构中换成,这意味着字符串解析,这是丑陋且容易出错的业务。