0
#include <iostream>
#include <string>

using namespace std;


int main()
{
   int num;
   cin >> num;
   string s;
   getline(cin, s);
   cout << s << " " << num << endl;
   return 0;
}

In this code if I input 3 and press enter, then s takes an empty string.

1) If it is taking the first character as a newline, then is there a possible solution of taking line as input after taking an integer as input?

2) If my input is 4567artyu then how it is deciding whether 7 has to go into the s or num ?

Meghdeep Ray
  • 5,262
  • 4
  • 34
  • 58
Ankit Gupta
  • 757
  • 7
  • 13

3 Answers3

3

I recommend that you always read complete lines of input from your users. It will cause the least confusion.

  • Ask for input.
  • Use std::getline to read a line of input.
  • If you don't want a string but, say, an integer, use std::stoi or (more general) boost::lexical_cast to safely convert the input to your desired target type. This is where you catch poor inputs and complain at the user.

I don't think that many users, if prompted for a number, would expect that entering 42bananas would be accepted as 42 and the bananas part be “remembered” for later. It will most likely be a typo and the user will be happy to be asked to correct it.

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
0

For taking line as input after taking integer as input you can consider removing the stray '\n' character from the stream.

#include <iostream>
#include <string>

using namespace std;

int main()
{
   int num;
   cin >> num;
   getchar();
   string s;
   getline(cin, s);
   cout << s << " " << num << endl;
   return 0;
}

This will do the trick.

For second question, it reads 4567 as integer, it will continue to read it as integer until limit of int is reached and if limit is reached it will not consider anything after that. Then it will put the maximum value of int in the variable num and null int the string s. If limit is not reached, then string will remain in the input stream as it is, and will be fetched by variable s.

dushyantashu
  • 523
  • 3
  • 9
  • 16
-2

Try using cin.clear before you accept string

Swapnil
  • 1,424
  • 2
  • 19
  • 30