2

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
Kila30
  • 33
  • 5
  • What do you think happens when you do `cin >> input2;` ? Also it is kinda tricky to mix formatted input with getline. – Captain Giraffe Feb 28 '18 at 23:28
  • @CaptainGiraffe I think of it as `input()` in Python – Kila30 Feb 28 '18 at 23:29
  • What is the first line with "1" supposed to signify? – Dan Korn Feb 28 '18 at 23:40
  • `>>` reads input until a whitespace character or line break and puts it in the variable provided. If you're coming from Python, you should get a [good book](https://stackoverflow.com/q/388242/9254539) since it's hard to learn proper C++ from things like online tutorials – eesiraed Feb 28 '18 at 23:41
  • @FeiXiang Yeah.. It's very stressful just by trying to learn online. Thanks for the suggestion though – Kila30 Feb 28 '18 at 23:44
  • Possible duplicate of [cin and getline skipping input](https://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Barmar Feb 28 '18 at 23:54
  • @FeiXiang: more importantly, `operator>>` ignores leading whitespace by default (unless you use `std::noskipws`), which includes line breaks, THEN it reads data until the next whitespace. – Remy Lebeau Mar 01 '18 at 01:05

1 Answers1

1

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.

FrankS101
  • 2,112
  • 6
  • 26
  • 40