【发布时间】:2014-02-03 03:18:12
【问题描述】:
所以我们有一个包含以下数据的文本文件:
年份 - 品牌 - 型号 - 价格
2011 雪佛兰 Tahoe 30588 美元
所有内容之间只有 1 个空格。价格前面有一个美元符号 ($)。即使它不在数据文件中,我们仍然必须在代码中包含里程。我不知道为什么。
如何从文本文件中获取这些信息?
我尝试了很多方法,但似乎都不起作用。
这是获取信息的代码:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <ctime>
#include "car.h"
using namespace std;
const int number=3;
const int maxPrice=25000;
int main()
{
int a;
string b; string c;
float d;
float e;
car cars [number];
int i, j;
float temp; //Price
int temp2; //Year
string temp3; //Make
string temp4; //Model
float temp5; //Miles
ifstream inFile; //declaring the File
inFile.open("carData.txt");
for(i=0; i<number; i++)
{
//cout << "Enter the YEAR of the car: ";
inFile >> a;
cars[i].setYear(a);
//cout << "Enter the MAKE of the car: ";
getline(inFile,b);
cars[i].setMake(b);
//cout << "Enter the MODEL of the car: ";
getline(inFile,c);
cars[i].setModel(c);
//cout << "Enter the number of MILES on the car: ";
inFile >> d;
cars[i].setMiles(d);
//cout << "Enter the PRICE of the car: ";
inFile >> e;
cars[i].setPrice(e);
//cout << " " << endl;
}
// ...
}
主要内容远不止于此,这只是为了获取所有数据。我真的整天都在为这件事烦恼。我见过很多不同的方法。
【问题讨论】:
-
你能缩进你的代码吗?
-
什么意思?它是缩进的
-
不是。位是但不是主要的。同时检查错误
-
“缩进”是什么意思?它是代码格式。我只展示了我整个代码的一个块。
-
您的问题被标记为 C,但像
inFile >> a;这样的示例代码暗示了 C++。你想要哪个一个。
标签: c++ int text-files ifstream getline