我有我不能改变的输入文件,具有略微不同线从输入文件C++读取与istream的操作符重载
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。解决这个问题最好的办法是什么?我想避免手动读取所有内容,因为这会破坏操作员重载的目的。
刚刚编辑了一下这篇文章。第一行读入并输出完全正常。第二行读入字符串“manufacturer2ndPart”中的“40”,而不是读入int milesPerGallon,从而使numPrevOwn成为内存中的任何值。 –
这些值是如何分开的? – Jonas
您必须知道输入文件的格式。例如,你怎么知道它没有与制造商“技术”一起输入“Supercar HTT”?应该有一条规则,例如“列至少分隔2个空格”或“列总是14个字符宽” – nwp