# algorithm - How to read multiple lines from user in C++?

So I'm doing acm programming practice problems and I'm always stuck on getting input from user. I'm using C++. So I need to read input from user and it could be multiple lines or a single line we don't know. So if the input is as follow:

2

1 2 3 4 5

2 2 2

The first line represent the number of games that the user play and the lines follow are the scores. The end of each game will be terminated by a newline. I need to read those lines and store it somewhere. How do I go about doing that? I've looked on websites and it seems like most people use scanf or cin or getline but I have no clue what those does.

Another example:

12 21

13 43

1 4

A C

0 0

Each line will contain the two number I need to add, separated by whitespace. When I see two zeros, the input is done. How do I read these and check if it's 0 0?

I tried something like:

``string num1;while (true) {getline(cin,num1);if (num1.empty()) {break;}}``

But it didn't work. Please help I think I know how to solve the problem but I can't the point of getting input from user. Thanks

Well, I learned this from doing online challenges and this is the way I do this when necessary.

First case, I think you have to declare N cases, so I have:

``````int N;
``````

Then, we need multiple numbers in each case, let's say 3. So I'll do this:

``````int score1[N];
int score2[N];
int score3[N];
``````

Finally, when you have to take input, you do this:

``````cin >> N;

for(int i = 0; i < N; i++)
cin >> score1[i] >> score2[i] >> score3[i];
``````

I'm not sure if this is the best way to do this, but this is how I do it when I am doing online challenges. Good luck!

This is kind of crude and bulky, but it should give you something to work with:

``````#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main() {
std::cout << "Enter two numbers (0 0 to exit): ";

string num1;
while (true) {
getline(cin, num1);

string buf;
stringstream ss(num1);
vector<string> tokens; // Create vector to hold the two numbers (separately)

// Split the two numbers (by the spaces)
while (ss >> buf)
tokens.push_back(buf);

cout << "Adding " + tokens[0] << " and " << tokens[1] << endl;

int sum = atoi(tokens[0].c_str()) + atoi(tokens[1].c_str());

cout << 0 + sum;

if (num1.empty()) {

break;
}
}
``````

}