结构数组写入文本文件
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;
会写入我的整个结构字段吗?
我是正确的,那是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的结构中换成,这意味着字符串解析,这是丑陋且容易出错的业务。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入