为了账号安全,请及时绑定邮箱和手机立即绑定

在CIN之后使用getline(CIN,s)

在CIN之后使用getline(CIN,s)

C++
jeck猫 2019-06-14 10:42:34
在CIN之后使用getline(CIN,s)我需要下面的程序来获取整个用户输入并将其放入字符串名称中:cout << "Enter the number: ";int number;cin >> number;cout << "Enter names: ";string names;getline(cin, names);带着cin >> number命令之前的命令。getline()命令(我猜这是问题所在),它不允许我输入名称。为什么?我听说了一些关于cin.clear()命令,但我不知道这是如何工作的,也不知道为什么这是必要的。
查看完整描述

3 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

cout << "Enter the number: ";int number;if (cin >> number){
    // throw away the rest of the line 
    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }
    cout << "Enter names: ";
    string name;
    // keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
    while (getline(cin, name))
        ...use name...}else{
    std::cerr << "ERROR reading number\n";
    exit(EXIT_FAILURE);}

在上面的代码中,这一点.。

    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }

.在数字只包含空格后检查输入行的其余部分。

为什么不直接使用忽略呢?

太冗长了,所以用ignore之后的小溪上>> x是一种推荐的替代方法,可以将内容丢弃到下一个换行符,但这样做可能会丢弃非空白内容,从而忽略文件中损坏的数据。您可能关心还是不关心,这取决于文件的内容是否可信,避免处理损坏数据的重要性等等。

那么你什么时候才会使用“清除”和“忽略”呢?

所以,std::cin.clear()(和std::cin.igore())并不是必需的,但是对于删除错误状态很有用。例如,如果您想给用户许多机会输入一个有效的数字。

int x;while (std::cout << "Enter a number: " &&
       !(std::cin >> x)){
    if (std::cin.eof())
    {
        std::cerr << "ERROR unexpected EOF\n";
        exit(EXIT_FAILURE);
    }

    std::cin.clear();  // clear bad/fail/eof flags

    // have to ignore non-numeric character that caused cin >> x to
    // fail or there's no chance of it working next time; for "cin" it's
    // common to remove the entire suspect line and re-prompt the user for
    // input.
    std::cin.ignore(std::numeric_limits<std::streamsize>::max());}

难道就不能用跳过或类似的简单点吗?

另一个简单但不成熟的替代方案ignore因为您最初的要求是使用std::skipws在阅读行之前跳过任何数量的空格.。

if (std::cin >> number >> std::skipws){
    while (getline(std::cin, name))
        ...

.但是如果它得到像“1E6”这样的输入(例如,一些科学家试图输入1,000,000,但C+只支持浮点数的表示法),你就不会接受number设为1,和E6的第一个值name..另外,如果您有一个有效的数字,后面是一个或多个空行,那么这些行将被默默地忽略。


查看完整回答
反对 回复 2019-06-14
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

cout << "Enter the number: ";int number;cin >> number;cin.ignore(256, '\n'); // remaining input characters up to the next newline character
                       // are ignoredcout << "Enter names: ";string names;getline(cin, names);


查看完整回答
反对 回复 2019-06-14
  • 3 回答
  • 0 关注
  • 940 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信