我希望输入两次,一个变量一个字符串和另一个字符,但它总是出现编译错误,我该如何解决这个问题。我试过cin.clear();但似乎在这种情况下不起作用。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
using std::string;
using std::getline;
int main(){
string name;
cout << "Please input a string." << endl;
getline (cin, name);
cout << "Hello, there, "<< name <<".\n";
char ccc;
cout << "Please input a character." << endl;
getline (cin, ccc);
cout << "This is a alphabet:" << ccc << endl;
return 0;
}
我希望输出结果如下:
Please input a string.
John
Hello, there, John.
Please input a character.
c
This is a alphabet:c
我以前用过cin.ignore();
。它应该清除缓冲区。 char也应该使用getchar而不是getline。
没有版本的getline()
接受char
作为其第二个参数。相反,您可能想要接受char*
的版本。您需要修改代码以读取包含一个字符的字符串。
在第二个上尝试使用getchar()而不是getline()。