根据用户输入的日期范围从TSV反向打印列

时间:2019-02-20 22:35:17

标签: c++ csv

您好,我有以下格式的TSV

Configure<Appsettings>

它一直持续到2018年12月31日。 现在,我必须根据用户输入以相反的顺序输出日期范围和WestElevation值,以便执行:

Date             EastStorage    EastElevation    WestStorage    WestElevation
01/01/2018          59.94           574             32.67           574.33 
01/02/2018          59.89           573.99          32.57           574.29
01/03/2018          59.89           573.97          32.44           574.24
01/04/2018          59.9            573.97          32.22           574.07

以下代码一遍又一遍地输出12/31/18的相应WestElevation值。

$ ./reverse-order
Enter earlier date: 05/29/2018
Enter later date: 06/02/2018

06/02/2018  590.22 ft
06/01/2018  590.23 ft
05/31/2018  590.24 ft
05/30/2018  590.26 ft
05/29/2018  590.32 ft

我认为使用数组来完成此任务可能是最简单的方法。但是我认为对于这种特定情况,我处理输入日期的逻辑有些偏离。如何修复代码以实现所需的输出?

解决方案:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <climits>
using namespace std;
int main()
{
    string date;
    string dates[365];
    string begindate;
    string enddate;
    bool isworking = false;
    double eastSt, eastEl, westSt, westEl;
    double elevation[365];
    for (int j = 0; j < 365; j++) {
        dates[j] = "empty";
    }
    cout << "Enter the earlier date: " << endl;
    cin >> begindate;
    cout << "Enter the later date: " << endl;
    cin >> enddate;
    ifstream fin("Current_Reservoir_Levels.tsv");
    if (fin.fail()) {
        cerr << "File cannot be opened for reading." << endl;
        exit(1); // exit if failed to open the file
    }
    string junk; // new string variable
    getline(fin, junk); // read one line from the file
    while (fin >> date >> eastSt >> eastEl >> westSt >> westEl) {
        // this loop reads the file line-by-line
        // extracting 5 values on each iteration
        fin.ignore(INT_MAX, '\n'); //skips to the end of line,
        //ignorring the remaining columns
        for (int i = 0; i < 365; i++) {
            if (begindate == date) {
                isworking = true;
                if (begindate == enddate) {
                    dates[i] = date;
                    elevation[i] = westEl;

                    isworking = false;
                }
            }
            else if (enddate == date) {
                dates[i] = date;
                elevation[i] = westEl;
                isworking = true;
            }
            if (isworking == true) {
                dates[i] = date;
                elevation[i] = westEl;
            }
        }
    }
    for (int a = 365; a >= 0; a--) {
        if (dates[a] != "emtpy" && elevation[a] != 0) {
            cout << dates[a] << " " << elevation[a] << endl;
        }
    }
    fin.close();
    return 0;
}

0 个答案:

没有答案