校招在线笔试做编程题的时候,输入的要求常常是不同的,记录每一次的输入,等以后在线笔试的时候就不慌了,噗哈哈
判断数字合辑
1、每次输入一个数字,当输入的不是数字的时候,循环结束
(注:当输入 回车、空格、tab键的时候,程序不会退出)
int main() {
//数据输入接口
int input = 0;
while (1) {
//如果input不是数字,则跳出循环
cin >> input;
if (cin.fail()) {
//not a number
cout << "当前输入非数字,程序退出" << endl;
break;
}
//number]
}
return 0;
}
2、输入一个string,判断string中是否全都是数字,如果存在非数字,则要求用户重新输入
#include <cctype>
#include<string>
#include<iostream>
using namespace std;
int main(void)
{
string str;
bool shuzi;
do
{
shuzi=true;
cout<<"请输入数字:"<<endl;
cin>>str;
for(string::iterator iter=str.begin();iter!=str.end();iter++)
{
if(!isdigit(*iter))
{
shuzi=false;
cout<<"输入含有非数字字符,请从新输入。"<<endl;
break;
}
}
}while(!shuzi);
system("pause");
return 0;
}
3、通过ascii码判断输入的char类型元素是否为数字
个位数的ascii码为 48(数字 0 的ascii码)到57(数字 9 的ascii码)之间。
#include<string>
#include<iostream>
using namespace std;
int main(void)
{
string str;
bool shuzi;
do
{
shuzi = true;
cout << "请输入数字:" << endl;
cin >> str;
for (string::iterator iter = str.begin(); iter != str.end(); iter++)
{
if (*iter < 48 || *iter > 57)
{
shuzi = false;
cout << "输入含有非数字字符,请从新输入。" << endl;
break;
}
}
} while (!shuzi);
system("pause");
return 0;
}