gpt4 book ai didi

C++:逐行逐字读取txt文件,每行的字数不均匀

转载 作者:行者123 更新时间:2023-11-28 01:35:13 30 4
gpt4 key购买 nike

晚上好

我有一个 txt 文件,其中包含有关某些汽车的信息。根据它的类型,每辆车都有自己的属性,例如:

类型1 车有名字,买价,租价。

2 型汽车有名称和购买价格。

3 型汽车有名称和购买价格。

类型4车有名称、购买价格、租赁价格和保险价格。

Type(Int)  Name(String)         Buy(Int)     Rent(Int)   Insurance(Int) 
1 toyota 5000 100
3 mazda 6000 130
2 mitsubishi 10000
1 honda 5000 110
4 ferrari 20000 220 1000

现在我只想读取文件并打印每辆车的类型,这样我就知道我的代码可以工作了。到目前为止我尝试过的是:

ifstream carsFile(cars.txt);

string carType;
string carName;
string carBuyPrice;
string carRentPrice;
string carInsPrice;
string line;

while (getline(carsFile, line))
{
istringstream buffer(line);

while (buffer >> carType >> carName >> carBuyPrice >> carRentPrice >> carInsPrice)
{
if (carType == "1")
{
cout << "Car type 1" << endl;
}
else if (carType == "2")
{
cout << "Car type 2" << endl;
}
else if (carType == "3")
{
cout << "Car type 3" << endl;
}
else
{
cout << "Car type 4" << endl;
}
}
}

carsFile.close();

上面的代码只适用于类型 2 和 3(它们具有相同的属性),即使行中的单词数量不均匀,我如何读取每种类型?

感谢任何帮助。

最佳答案

我强烈建议为文件中的记录建模一个结构。接下来,重载 operator>> 来读取字段。
示例:

struct Car_Info
{
int type;
std::string manufacturer;
int buy_price;
int rent_price;
int insurance_price;
// Here's the kicker
friend std::istream& operator>>(std::istream& input, Car_Info& ci);
};

std::istream& operator>>(std::istream& input, Car_Info& ci)
{
std::string text_line;
std::getline(input, text_line);
if (input)
{
std::istringstream text_stream(text_line);
// Initialize optional fields
ci.rent_price = 0;
ci.insurance_price = 0;
text_stream >> ci.type
>> ci.manufacturer
>> ci.buy_price;
>> ci.rent_price
>> ci.insurance_price;
}
}

你的输入循环看起来像:

std::vector<Car_Info> database;
Car_Info car;
while (input_file >> car)
{
database.push_back(car);
}

使用结构代替并行数组,减少同步错误带来的缺陷。

一个字符串用于读取一条文本记录。任何读取问题(例如 eof)都会改变输入流的状态,因此使用字符串流来隔离由缺失字段产生的错误。

关于C++:逐行逐字读取txt文件,每行的字数不均匀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49600852/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com