如何在不同的行中多次获得cin?

问题描述 投票:-1回答:3

我希望输入两次,一个变量一个字符串和另一个字符,但它总是出现编译错误,我该如何解决这个问题。我试过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
c++ cin
3个回答
2
投票

我以前用过cin.ignore();。它应该清除缓冲区。 char也应该使用getchar而不是getline。


1
投票

没有版本的getline()接受char作为其第二个参数。相反,您可能想要接受char*的版本。您需要修改代码以读取包含一个字符的字符串。


0
投票

在第二个上尝试使用getchar()而不是getline()。

© www.soinside.com 2019 - 2024. All rights reserved.