Home > Enterprise >  How to properly use >> to get columns of an input file in cpp?
How to properly use >> to get columns of an input file in cpp?

Time:05-20

I'm pretty new to cpp and I've been struggling on this for hours, none of my research attempts were lucky.

I have a few .txt files with the following structure:

07.07.2021 23:11:23 01

08.07.2021 00:45.44 02

...

I want to create two arrays, one containing the dates and one containing the times. However all I've accomplished so far are arrays containing the last element of each column and the rest is empty (Example see below). The Code looks like this:

std::vector<string> txt_to_time(std::ifstream raw, int num, int what){

    std::vector<string> date(num);
    std::vector<string> time(num);
    std::vector<string> irrelevant(num);
        
    string str;
    for (int i=0; i<num; i  )
    {
        while (std::getline(raw,str))
        {
            raw >> date[i] >> time[i] >> irrelevant[i];
        }
    }
    
    if (what == 0)
    {
        return time;
    }
    
    return date;
}

I think I am messing something up in the while-loop but I don't really know how to fix it.

When I try to print every element of the vector the output I get is

10:45:22






(int) 0

Thanks for spending time to read my question, every answer is appreciated!

CodePudding user response:

Your issue is that you use while and std::getline for no reason. Combining std::getline and << leads to issues, and you also try to read whole file into first elements of your vectors because of the while loop.

Since unsuccessful read will return empty string (which are already in your vectors), you can skip any checks if read was successful and just do:

for (int i=0; i<num; i  )
{
    raw >> date[i] >> time[i] >> irrelevant[i];
}
  •  Tags:  
  • c
  • Related