4

consider this code snippet in c++ -

string str;
cin>>str;

If I simply press enter at this stage, the pointer moves to next line but keep waiting for the input even if I intentionally want to input an empty string.

My objective is to read a word. And If I press enter, it should be taken as a empty string.

  • Don't use cin because it doesn't read a string - it reads a word. Use getline to read a string. – Jerry Jeremiah Nov 13 '15 at 04:49
  • @JerryJeremiah this behaviour can be changed with [std::noskipws](http://en.cppreference.com/w/cpp/io/manip/skipws) as stated in [mnciitbhu's answer](https://stackoverflow.com/a/33687470/2932052) . – Wolf Dec 13 '17 at 14:01

2 Answers2

6

Use std::getline:

std::string str;
std::getline(std::cin, str);
Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • I have included bits/stdc++.h – Vishal Sharma Nov 13 '15 at 05:04
  • Its working. The actual problem was that I was reading an integer before reading the string. using cin.ignore solved the problem. – Vishal Sharma Nov 13 '15 at 05:23
  • @VishalSharma The actual problem is the mere use of `operator>>`. Don't mix calls to `operator>>` and `getline()`. Actually, just stop using `operator>>` already – it's quirky, it's clumsy, it's hard to use correctly. If you want to read an integer, just use `getline()` and parse the input string using `std::stoi()`. – The Paramagnetic Croissant Nov 13 '15 at 07:29
2

There are two ways :

Use std::getline()

std::string str;
getline(cin, str);

Or using std::noskipws

std::string str;
cin >> noskipws >> str;

Don't forget to use cin.ignore().

0x6773
  • 1,116
  • 1
  • 14
  • 33