Trying to use two separate instances of getline () to populate two separate vectors

I am working on this HackerRank issue .

In my problem, I am trying to use getline()two different input vectors to enter two different lines of input for organization purposes.

The input is as follows:

9 6 2015
6 6 2015

Here is my code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
#include <sstream>
using namespace std;

int main() {
    vector<int> expecDate;
    vector<int> retDate;
    string firstLine;
    string secLine;
    while(getline(cin, firstLine)){
        stringstream ss(firstLine);
        while(getline(ss,firstLine,' ')){
            int num = atoi(firstLine.c_str());
            retDate.push_back(num);
        }
    }
    while(getline(cin, secLine)){//want to use this second instance of getline() to fill the expecDate vector
        stringstream ss_2(secLine);
        while(getline(ss_2,secLine,' ')){
            int num_2 = atoi(secLine.c_str());
            expecDate.push_back(num_2);
        }
    }
    int year_e, month_e, day_e;
    int year_a, month_a, day_a;

    year_a = retDate[2];
    month_a = retDate[1];
    day_a = retDate[0];
    year_e = retDate[5];//want this to be expecDate[2]
    month_e = retDate[4];//want this to be expecDate[1]
    day_e = retDate[3];//want this to be expecDate[0]

    if(year_a <= year_e && month_a <= month_e && day_a <= day_e){
        cout<<"0"<<endl;
    }else if(year_a > year_e){
        cout<<"10000"<<endl;
    }else if(month_a > month_e){
        int total_m = 500*(month_a - month_e);
        cout<<total_m<<endl;
    }else if(day_a > day_e){
        int total_d = 15*(day_a - day_e);
        cout<<total_d<<endl;
    }


    return 0;
}

This code returns the correct output, I'm just wondering how I can do this, so I can use both vectors instead getline(), just filling the first one completely vector.

Update: with this code, expecDate does not populate at all. Attempting to refer to any of its members causes a segmentation error.

+4
source share
1 answer

while .

while(getline(cin, firstLine)){
   ...
}

cin, .

while(getline(cin, secLine)){
   ...
}

, cin .

while. if.

if (getline(cin, firstLine)){
   ...
}

if (getline(cin, secLine)){
   ...
}
+2

Source: https://habr.com/ru/post/1692390/


All Articles