如何在C ++中加倍时间值

时间:2015-12-30 19:43:03

标签: c++ c++11

任务是从txt文件加倍一段时间" time.in"以HH:MM:SS的格式(例如12:22:03)并以" time.out"中的相同格式(例如24:44:06)输出它。我无法跳过":"输入中的字符。这是我的代码:

#include <fstream>
#include <cmath>
#include <stdio.h>
using namespace std;

int main() {
FILE *fin = fopen("time.in", "r");
FILE *fout = fopen("time.out", "w");
char c;
double hrs, mins, secs;
double fhrs = 0, fmins = 0, fsecs = 0;

ifstream input;
input.open("time.in");
input>> hrs;
c = fgetc(fin); //what should this be? I can't get it to work properly.
input>> mins;
c = fgetc(fin);
input>> secs;
input.close();

fhrs = hrs * 2;
if (secs < 30) {
    fsecs = secs * 2;
    if (mins < 30)
        fmins = mins * 2;
    else {
        fmins = abs(60 - (mins * 2));
        fhrs++;
    }
} else {
    fsecs = abs(60 - (secs * 2));
    fmins++;
    if (mins < 30)
        fmins += mins * 2;
    else {
        fmins += abs(60 - (mins * 2));
        fhrs++;
    }
}

ofstream output;
output.open("time.out");
output << fhrs <<":"<< fmins <<":"<< fsecs <<endl;
output.close();

return 0;

}

1 个答案:

答案 0 :(得分:0)

使用C ++或C中的一个文件处理例程。混合FILEifstream肯定会导致问题。

ifstream input;
input.open("time.in");
input>> hrs;
input.get();
...

应该做的伎俩。 如果你想挑剔:

if (input.get() != ':') ... complain about bad input ...