这次我将尝试更具描述性,我一直在进行研究,但似乎无法弄清楚。我有一个名为 Time 的类,如下所示:
class Time{
private:
int minutes;
int hours;
public:
Time();
Time(int h, int m);
void addMin(int m);
void addHour(int h);
void setTime(int m, int h);
void reset(int h=0, int =0);
Time sum(const Time &t) const; //Add one time to another time.
Time sum(int m) const;
Time operator*(double other) const;
void show() const;
};
我有一个看起来像这样的文件:
90 1 3.0
1 1 100.0
2 34 5.1
每行中的第一个数字是 times[i].hours
,第二个数字是 times[i].minutes
,第三个值是 double 值存储在 math[i]
中。由于变量是私有(private)的,我需要调用“setTimeHours(int h)”和 setTimeMinutes(int m)
,但我不确定该怎么做。这就是我的。
int number_of_lines = 0;
std::string line;
while (std::getline(inputFile, line)){
++number_of_lines;
}
Time times[number_of_lines];
double math[number_of_lines];
std::string input;
for(int loop=0;loop<number_of_lines;loop++){
std::getline(inputFile, input);
stid::istringstream(input) >> times[i].minutes >> times[i].hours >> math[i];
}
我需要帮助的线路是:
stid::istringstream(input) >> times[i].setTimeMinutes(//what goes here?) >> times[i].setTimeHours(//what goes here?) >> math[i];
如果,那当然行得通?谢谢!
最佳答案
只需为 Time
创建一个输入运算符输入行将变为
if (!(std::istringstream(input) >> std::skipws >> time[i])) {
// report input error
}
搞笑std::skipws
需要获得非 const
引用来自临时 std::istream&
的流 ( std::istringstream
)只能绑定(bind)到 const&
(这是有效的,因为使用的输入运算符恰好是 std::istream
的成员并返回 std::istream&
)。
您只需为您实现一个输入运算符Time
类,例如:
std::istream& operator>> (std::istream& in, Time& time) {
int value;
if (in >> value) {
time.setTimeMinutes(value);
}
return in;
}
可能输入运算符看起来比这复杂一点,但基本思想保持不变。
关于c++ - 将一行文件读入一个对象中的2个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551677/