Separating alternating lines of a text file into two different but corresponding arrays C++

1118 views c++

Ok, so I have been trying to figure this out for a couple hours and have literally gotten nowhere. None of the answers to similar questions I found make any sense to me. I assume because we haven't gotten that far into the curriculum yet.

I need to take an input text file formatted with responses and categories like so,


and put it into two different arrays (responses[], categories[]). I have to use a function to do this. My instructor gave us the function declarations but not definitions so for this we have,

void readResponses(ifstream &infile, string responses[], string categories[], int &size)

I can open a file and put it into an array no problem. I know how to use the array and print it out, etc. I just don't know how to separate the two. Is there a way to use getline and put every other line into an array? Sorry if this is a repetitive question but thank you in advance for your help.

answered question

What is stopping you from reading two lines and putting one into each array?

Because...I like banging my head against brick walls. I bow to your genius. Also, thanks.

1 Answer


I think you might be stuck in a particular mode of thinking, based on how you normally read lines. A common way to read a text file is one line at a time in a loop as follows:

void foo(std::istream& inStream)
    std::string line;
    while (std::getline(inStream, line))
        // Do stuff with line

Now, if you're expecting that every input is two lines of text, just read two lines at a time:

void foo(std::istream& inStream)
    std::string response, category;
    while (std::getline(inStream, response) && std::getline(inStream, category))
        // Do stuff with response and category

posted this

Have an answer?


Please login first before posting an answer.