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.

2
  • Don't use cin because it doesn't read a string - it reads a word. Use getline to read a string. Commented Nov 13, 2015 at 4:49
  • @JerryJeremiah this behaviour can be changed with std::noskipws as stated in mnciitbhu's answer . Commented Dec 13, 2017 at 14:01

2 Answers 2

7

Use std::getline:

std::string str;
std::getline(std::cin, str);
Sign up to request clarification or add additional context in comments.

3 Comments

I have included bits/stdc++.h
Its working. The actual problem was that I was reading an integer before reading the string. using cin.ignore solved the problem.
@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().
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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.