c++ - 结构数组写入文本文件

标签 c++ struct writetofile

我的结构数组的文件写入函数有问题。我收到错误,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/

相关文章:

c++ - 当重载函数作为参数涉及时,模板参数推导如何工作?

c++ - QT中的非初始化指针

c++ - 将字节数组转换为十六进制时的空格 std::string C++

确保元素位于结构开头的 C 宏

c++ - 使用 malloc 在 C++ 中动态分配结构

c++ - 作者在解释 C++ 中的堆栈和堆时是否犯了错误,或者我误读了什么?

c - 如何判断输出时使用的是什么类型的union?

scala - writeAsCSV() 和 writeAsText() 是意外的

java - 写入文件java

ios - 从 URL 下载图像并存储在设备中(可以是 iPod 中的“照片”文件夹),而不是在应用程序中