I am new to C++. I was looking into getting string inputs from user terminal, I observed something with std::getline and std::cin and I cannot find a resolution to.
The thing is whenever I use a std::cin before getline, my code skips over the std::getline. Here is an example:
#include <iostream>
#include <string>
using namespace std;
int main(){
int age;
string full_name;
cout << "Enter your full name" << endl;
getline(std::cin, full_name);
cout << "Enter your age" << endl;
cin >> age;
cout << "Your full name is: " << full_name << endl;
cout << "Your age is: " << age << endl;
return 0;
}
The terminal output to the below code is:
Enter your full name
Buggs Bunny
Enter your age
28
Your full name is: Buggs Bunny
Your age is: 28
This is the correct output and it is something I expect.
But now if I move the cin statement above getline, my code skips the getline completely. Here is an example:
#include <iostream>
#include <string>
using namespace std;
int main(){
int age;
cout << "Enter your age" << endl;
cin >> age;
string full_name;
cout << "Enter your full name" << endl;
getline(std::cin, full_name);
cout << "Your full name is: " << full_name << endl;
cout << "Your age is: " << age << endl;
return 0;
}
Here is the terminal output and it skips getline:
Enter your age
28
Enter your full name
Your full name is:
Your age is: 28
OS: MacOs Big Sur 11.2.3, M1 Macbook C++ and gcc version details:
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.5 (clang-1205.0.22.11)
Target: arm64-apple-darwin20.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Any help is appreciated. Thanks a ton in advance.