【发布时间】:2025-12-04 17:45:01
【问题描述】:
我有一个无法更改的输入文件,其中的行略有不同
Supercar HTT Technologies 10 2
Motorcycle Honda 40 1
...
为了将值读入我的数据结构,我重载了 >> 运算符,如下所示:
class Vehicles{
private:
string type; //type of vehicle, i.e. car/motorcycle
string manufacturer;
string manufacturer2ndPart //not a good idea, but this is what I'm using
//to get the second part of the manufacturer ("Technologies")
int milesPerGallon;
int numPrevOwn //number of previous owners
public:
...
friend istream &operator >> (istream &is, Vehicles &Vec){
is >> Vec.type >> Vec.manufacturer >> Vec.milesPerGallon >> Vec.numPrevOwn;
return is;
}
};
这在第一行工作得很好,但在输入文件的第二行就崩溃了,因为它试图将“40”读入manufacturer2,而不是milesPerGallon。解决这个问题的最佳方法是什么?我想避免手动读取所有内容,因为这违背了我的运算符重载的目的。
【问题讨论】:
-
刚刚编辑了这篇文章。第一行被读入并完全正常输出。第二行将“40”读入字符串manufacturer2ndPart,而不是intmilesPerGallon,因此将numPrevOwn 保留为内存中的任何值。
-
值是如何分开的?
-
您必须知道输入文件的格式。例如,你怎么知道它不是带有制造商“技术”的“超级跑车 HTT”?应该有一个规则,例如“列至少用 2 个空格分隔”或“一列总是 14 个字符宽。
-
输入文件值之间用 3 个空格分隔。
-
您的 >> 运算符实现必须更复杂,我会说它应该调用 get_type()、get_manufacturer() 等,并且您应该在内部处理案例(“类型由多个单词组成”, “制造商由多个词组成”等)
标签: c++ input operator-overloading istream