C++ sample code for validating user input

C++ sample code for validating user input

This article introduces c++ to verify the legality of user input, which is used to detect and limit user input values. Including: 1. Restrict user input to be an integer (positive or negative integer); 2. Restrict user input to be a positive integer; 3. Restrict user input to be a positive number (may contain decimals); 4. Restrict user input to a number; 5. Restrict Can only be entered as English letters.

Tip : The following program requires the compiler to support the c++11 standard.

[If you use Dev-C++, you need to set: Open the "Tool [T]→Compile Options [C]" menu, add -std=c++11, and then press the "OK" button to take effect. See the red circle in the figure below:

1. Limit user input to integers

It can be a positive or negative integer, and there are several source codes available for selection

Source code 1 :

#include <iostream>
using namespace std;
//判断输入的字符串是否为整数,直至合规才返归其值
int judge(int temp)
{      
	//对输入的合法性进行判断并返回有效的输入
	//int temp;
	cin.sync();    //清空输入流缓冲区
	cin>>temp;
	while(1)
	{
		if(cin.fail()||cin.bad()||cin.get()!='\n')    //验证输入是否合法,其中cin.fail()和cin.bad()解决输入字符串和溢出的问题
			cout<<"错误!请重新输入:"<<endl;    //cin.get()检查输入流中是否还有字符(如果有就表示输入的是形如123r或12.3的错误
		else break;      //输入合法则跳出循环
		cin.clear();    //清空输入流缓冲区标志位,以免影响下次输入
		cin.sync();     
		cin>>temp;
	}
	return temp;
}

int main()
{
	cout<<"请输入整数:"<<endl;
	int a;	
	cout<<"合规的输入:"<<judge(a)<<endl;
	return 0;
}

The running effect is as follows:

Source code 2 :

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

//是整数返回1,否则返回0 
bool isNumber3(const string& str)
{
    return str.find_first_not_of( "-0123456789" ) == string::npos &&
        str.front() != '.' && str.back() != '.';
}

int main(){
    string str;
    cout<<"请输入整数:"<<endl;
	cin>>str;
    while(!isNumber3(str)){
		cout<<"请输入整数,不要输入字母:"<<endl;
		cin>>str;
	}
    cout <<"合规输入:"<<str<<endl;
   
    //exit(EXIT_SUCCESS);
    return 0; 
}

The running effect is as follows:

2. Limit user input to positive integers

There are several source codes available for selection

source code 1

#include <iostream>
#include<string>
using namespace std;
//判断输入的字符串是否为正整数,若是,则合规返归其值 ,否则给出提示继续 
int CheckNum(int& n)
{
    int i;
    string x;  //用来接受输入
    bool flag = false;
    while (cin >> x) {
        for (i = 0; i < x.size(); ++i) {
       		 //判断是否为中文
            if (x[i] & 0x80) {
                cout << "\n输入错误,请重新输入正确的数字: ";
                break;
            }
            //判断是否为字母或者其它字符
            if (!isdigit(x[i])) {
                cout << "\n输入错误,请重新输入正确的数字: ";
                break;
            }
        }
        if (i == x.size()) {
            break;   //如果字符串中所有字符都合法,则退出while循环
        }
    }
    n = atoi(x.c_str()); //将string字符串转化为整数
    return n;    
}

int main()
{
    int m,n;
    while (true) {
        cout << "请输入正整数:";
        n=CheckNum(m);
        cout <<"合规输入:"<<n<<endl;
        break;  //退出循环 		
    }
}

The running effect is as follows:

source code 2

#include<iostream>
#include<algorithm>
#include<cstring> 
#include<stdlib.h>  //为了使用 c_str() 函数 
using namespace std;
//将string转为char数组并判断输入是否为正整数
int check1(string s){
	char a[s.length()];
	strcpy(a,s.c_str());
	int i; 
	for(i = 0;i<s.length();i++){
		//如果不是数字
		if(!isdigit(a[i])){
			return -1; 
		}
	}
	return 0; 
}

//string 转 int
int s2i(string s)
{
	return atoi( s.c_str() );
}

int main()
{
    string n0;//判断用户输入用
	int n;//真正存储的变量
    cout<<"请输入:"<<endl;
    cin>>n0;
    //判断输入的n0是否符合要求
	while(check1(n0)){
		cout<<"请输入正整数,不要输入负数或者小数或字母:"<<endl;
		cin>>n0;
	}
    n = s2i(n0);//string转为int存储 
    cout <<"合规输入:"<<n<<endl;

}

The running effect is as follows:

Source code 3 :

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

//是正整数返回1,否则返回0 
bool isNumber(const string& str)
{
    return !str.empty() &&
        find_if(str.begin(), str.end(),
            [](unsigned char c) { return !isdigit(c); }) == str.end();
}

int main(){
    
    string str;
    cout<<"请输入正数:"<<endl;
	cin>>str;
    while(!isNumber(str)){
		cout<<"请输入正整数,不要输入负数或者小数或字母:"<<endl;
		cin>>str;
	}
    cout <<"合规输入:"<<str<<endl;
   
    //exit(EXIT_SUCCESS);
    return 0; 
}

The running effect is as follows:

3. Limit user input to positive numbers

can contain decimals

Source code 1 :

#include<iostream>
#include<algorithm>
#include<cstring> 
#include<stdlib.h>  //为了使用 c_str() 函数 
using namespace std;
//将string转为char数组并判断输入是否为正数
int check2(string s){
	char a[s.length()];
	strcpy(a,s.c_str());
	int i; 
	for(i = 0;i<s.length();i++){
		//如果不是数字且不是小数点 
		if((!isdigit(a[i])) && (a[i]!='.')){
			return -1; 
		}
	}
	return 0; 
}

//string 转 double
double s2d(string s)
{
	return atof( s.c_str() );
}

int main(){
	string n0;//判断用户输入用
	double n;//真正存储的变量
    cout<<"请输入正数:"<<endl;
    cin>>n0;
    //判断输入的n0是否符合要求
	while(check2(n0)){
		cout<<"请输入正数,不要输入负数或字母:"<<endl;
		cin>>n0;
	}
    n = s2d(n0);//string转为double存储 
    cout <<"合规输入:"<<n<<endl;
}

The running effect is as follows:

Source code 2 :

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

//是正数返回1,否则返回0 
bool isNumber3(const string& str)
{
    return str.find_first_not_of( ".0123456789" ) == string::npos &&
        str.front() != '.' && str.back() != '.';
}

int main(){
    string str;
    cout<<"请输入正数:"<<endl;
	cin>>str;
    while(!isNumber3(str)){
		cout<<"请输入正数,不要输入负数或字母:"<<endl;
		cin>>str;
	}
    cout <<"合规输入:"<<str<<endl;   
    return 0; 
}

The running effect is as follows:

4. Limit user input to a number

Include positive and negative integers, positive and negative decimals, but cannot contain letters

The source code is as follows

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

//是数返回1,否则返回0 
bool isNumber3(const string& str)
{
    return str.find_first_not_of( "+-.0123456789" ) == string::npos &&
        str.front() != '.' && str.back() != '.';
}

int main(){
    string str;
    cout<<"请输入数:"<<endl;
	cin>>str;
    while(!isNumber3(str)){
		cout<<"请输入数,不要输入字母:"<<endl;
		cin>>str;
	}
    cout <<"合规输入:"<<str<<endl;
   
    //exit(EXIT_SUCCESS);
    return 0; 
}

The running effect is as follows:

5. Only English letters can be input

The source code is as follows

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

//是英语字母返回1,否则返回0 
bool isNumber3(const string& str)
{
    return str.find_first_not_of( "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" ) == string::npos &&
        str.front() != '.' && str.back() != '.';
}

int main(){
    string str;
    cout<<"请输入英语字母:"<<endl;
	cin>>str;
    while(!isNumber3(str)){
		cout<<"请输英语字母:"<<endl;
		cin>>str;
	}
    cout <<"合规输入:"<<str<<endl;
   
    //exit(EXIT_SUCCESS);
    return 0; 
}

The running effect is as follows:

OK!

Reference 
https://www.jiyik.com/tm/xwzj/prolan_3518.html

Guess you like

Origin blog.csdn.net/cnds123/article/details/130322634