std::cin cannot read a line with whitespaces, for example John doe. It will only read John and doe remains in buffer for std::cin.
If we want to take a whole line as input with whitespaces, we can use function std::getline. std::getline takes std::cin and a string variable as arguments and stores input in string variable. Following program shows this.
#include <iostream>
#include <string>
#include "../helpers/stdout.h"
int main(int argc, char const *argv[])
{
std::string fullName{};
std::cout << "Enter your fullname: ";
std::getline(std::cin, fullName);
print(fullName);
return 0;
}This should print following output:
Enter your fullname: john doe
john doe
There is one thing to remember when using std::getline. It does not ignore leading whitespace character (such as newlines, spaces, tabs). When std::cin contains an input like \njohn doe, std::getline encounters \n and it ends reading further.
#include <iostream>
#include <string>
#include "../helpers/stdout.h"
int main(int argc, char const *argv[])
{
std::string fullName{};
int temp;
std::cin >> temp;
std::cout << "Enter your fullname: ";
std::getline(std::cin, fullName);
print(fullName);
return 0;
}When we run this program and give input 1 and press enter, std::cin receives 1\n where it stores 1 in temp. Next when std::getline reads, std::cin receives \n and std::getline thinks that an empty string has been entered.
Output of the above program:
1
Enter your fullname:
To avoid this issue, we can use std::ws O manipulator for std::cin. It makes std::cin ignore any leading whitespace. Following line
std::getline(std::cin >> std::ws, fullName);solves the problem.