简体   繁体   中英

Getline() for the second line and split by space - C++

I'm trying to solve a problem that requires multiple inputs from the users. I'm used to Python, so the C++ syntax is a bit more complex to me.

What I mean:

Input:

1

30 40 50

Output:

30 40 50

I didn't find a single solution to this and I've been trying to find it all day.

What I've tried:

#include <iostream>
using namespace std;

int main()
{
    int input1; cin >> input1;
    string input2;
    cin >> input2;
    getline(cin, input2);
    cout << input2;
}

And I don't seem to understand the getline() method properly. What I get:

Output:

 40 50

Expected Output:

30 40 50

cin >> input2;

This reads 30.

getline(cin, input2);

and this reads the rest of the line. Simply change the line:

cin >> input2;

for:

cin.ignore();

that way you don't read the first number in the second line and ignore the enter key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM