0

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!

Angelo F
  • 3
  • 2
  • 1
    Please note when using the `[]` operator to insert your data into a vector that "Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior." source: https://en.cppreference.com/w/cpp/container/vector/operator_at – Tommy Andersen May 20 '22 at 10:57
  • Not clear what you are seeking. Using `>>` with an `istream`, by default, stops reading a numeric value when it encounters whitespace, so `raw >> date[i] >> time[i] >> irrelevant[i];` will read three values. There are other serious problems in your code as shown, but your description doesn't even hint at those - suggesting the code you posted is different from your actual code. Voting to close as you're effectively requiring folks to guess what your problem is, or what you are seeking. – Peter May 20 '22 at 11:01
  • I would just read the lines and split them in half using [space] as delimiter. Here on [how to split a string](https://stackoverflow.com/a/46931770/4165552) – pptaszni May 20 '22 at 11:02

1 Answers1

2

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];
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52