为什么程序不停止输入? [英] Why does the program not stop for the input?

查看:117
本文介绍了为什么程序不停止输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我刚刚开始学习c ++一个小时前,我遇到这个错误:

Hello all i just started learning c++ an hour ago and I'm encountering this error :

#include "stdafx.h"
#include <iostream>
#include <string>

int main()
{
    using namespace std;
    string name;
    int age;
    cout << "How old are you ?";
    cin >> age;
    cout << "Awesome, what's your name?";
    getline(cin, name);
    cout << "Nice name, " << name << "!";

    return 0;

}

getLine )被完全忽略,并直接进入下一个cout并以如下方式结束:

getLine(cin,name) is being totally ignored and directly goes to the next cout and ends like this :

http://puu.sh/9drtu/80449b62ac.png

感谢。

推荐答案

阅读文档

注意
在以空格分隔的输入后立即使用,例如 int n; std :: cin>> n; , getline 通过 operator>> 消耗输入流上剩余的结束字符>,并立即返回。一个常见的解决方案是使用 cin.ignore(std :: numeric_limits< std :: streamsize> :: max(),'\\\
');
,然后切换到面向行的输入。

Notes: When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.

这篇关于为什么程序不停止输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆