如何避免char输入int变量? [英] How Can I avoid char input for an int variable?
问题描述
下面的程序显示了一个int值被输入并被同时输出。但是,当我输入一个字符时,它进入一个无限循环,显示输入的前一个'int'值。如何避免输入字符?
The program below shows a 'int' value being entered and being output at the same time. However, when I entered a character, it goes into an infinite loop displaying the previous 'int' value entered. How can I avoid a character being entered?
#include<iostream>
using namespace std;
int main(){
int n;
while(n!=0){
cin>>n;
cout<<n<<endl;
}
return 0;
}
推荐答案
循环:
cin进入失败状态,使其忽略对其的进一步调用,直到错误标志和缓冲区重置。
cin goes into a failed state and that makes it ignore further calls to it, till the error flag and buffer are reset.
cin.clear();
cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream.
检查输入是否为数字:
在你的代码中,即使一个非int类型也会被转换为int。没有办法检查输入是否为数字,不输入到一个字符数组,并调用 isdigit()
函数每个数字。
In your code, even a non-int type gets cast to int anyway. There is no way to check if input is numeric, without taking input into a char array, and calling the isdigit()
function on each digit.
函数 isdigit()可用于告诉数字和字母分开。此函数位于< cctype>
头中。
The function isdigit() can be used to tell digits and alphabets apart. This function is present in the <cctype>
header.
一个is_int()函数看起来像这样。
An is_int() function would look like this.
for(int i=0; char[i]!='\0';i++){
if(!isdigit(str[i]))
return false;
}
return true;
这篇关于如何避免char输入int变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!