It requires to explain how the std::string
and std::getline
handle the whitespace characters separately. And I run the code that solution provides but didn't get the result expected.
Here's the code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word, line;
cout << "choose:1 string,2 getline" << endl;
char ch;
cin >> ch;
if (ch == '1') {
cout << "Please input:Welcome to C++family!" << endl;
cin >> word;
cout << "Effective string:" << word << endl;
return 0;
}
cin.clear();
cin.sync();
if (ch == '2') {
cout << "Please input:Welcome to C++family!" << endl;
getline(cin, line);
cout << "Effective string:" << endl;
cout << line << endl;
return 0;
}
cout << "Error!" << endl;
return -1;
}
When I input "1" the result is no problem.But when I input "2", it does not let me input and show like the under line:
2
Please input :Welcome to C++family!
Effective string:
Enter any key to continue......
I can't understand why it runs like this and what is the mistake.
Please help me, thank you.