c++ - 将一行文件读入一个对象中的2个变量

标签 c++ file io

这次我将尝试更具描述性,我一直在进行研究,但似乎无法弄清楚。我有一个名为 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/

相关文章:

c++ - double 和其他 float

c++ - 程序在图形 shell 中的运行速度比在命令 shell 中快

php - 读取制表符和换行符分隔(多维)平面文件数据库

haskell - 如何终止在 `IO` monad 中运行的计算?

io - 似乎无法从运行中获取非字符串输出

c++ - 读取 BSDF 数据格式

java - 使用 FileReader 时解决 IOException、FileNotFoundException

python - RTTM文件格式

c# - 将 MemoryStream 保存到文件或从文件加载 MemoryStream

c++ - opencl c++ API 包装器中的 clFinish 等价物是什么?