Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read an empty string in c++?

Tags:

c++

string

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.

like image 227
Vishal Sharma Avatar asked Oct 19 '25 13:10

Vishal Sharma


1 Answers

Use std::getline:

std::string str;
std::getline(std::cin, str);
like image 190
Felix Glas Avatar answered Oct 21 '25 03:10

Felix Glas