Sco*_*oop 6 c++ integer character cin
下面的程序显示输入的"int"值并同时输出.但是,当我输入一个字符时,它进入一个无限循环,显示输入的前一个'int'值.如何避免输入字符?
#include<iostream>
using namespace std;
int main(){
int n;
while(n!=0){
cin>>n;
cout<<n<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
无限循环的原因:
cin进入失败状态,这使得它忽略对它的进一步调用,直到错误标志和缓冲区被重置.
cin.clear();
cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream.
Run Code Online (Sandbox Code Playgroud)
检查输入是否为数字:
在你的代码中,即使非int类型也会被转换为int.无法检查输入是否为数字,无需将输入输入char数组,并isdigit()在每个数字上调用该函数.
函数isdigit()可用于分辨数字和字母.此功能出现在<cctype>标题中.
is_int()函数看起来像这样.
for(int i=0; char[i]!='\0';i++){
if(!isdigit(str[i]))
return false;
}
return true;
Run Code Online (Sandbox Code Playgroud)