Reading Strings that Contain White Spaces

The std::getline() functions reads data from an input stream and writes it to a string object. Unlike cin’s >> operator, getline() also reads white spaces, which makes it useful for reading strings that contain blanks. For example:

 #include #include int main(){ std::string name; cout<<"enter first name and last name: "; std::getline(std::cin, name);}

getline() has three parameters, the third of which is a delimiter serving as a string terminator. By default, the delimiter's value is '
'. You can override this value and define a different delimiter. For example, you can define the sign ' ' (tab) as the delimiter:

 std::getline(cin, name, '	');
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: