首页 > 解决方案 > 当我第二次调用函数两次时,函数运行时我无法输入

问题描述

#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;

const int Length = 61;

void getinput (char []);


int main()
{
char a[Length];
char b[Length];

getinput(a);
getinput(b);


}

void getinput (char input[]){
    
    cout << "Enter Input: ";
    cin.get(input, 60);
    cout << "You Entered " << input <<endl;
    
}

当我运行此代码时,我无法输入我的第二个输入吗?我不明白我所做的只是两次调用相同的函数。

这是得到的输出:

输入输入:嗨

您输入:您好

输入输入:您输入

标签: c++

解决方案


那是因为cin缓冲输入

cin.get(input, 60);

第二次调用会将第一次调用留下的换行符解释为其输入。

为防止此类错误,您可以getline改用:

std::cin.getline (input,60);

推荐阅读