检查输入有效性

Checking for Input Validity?

本文关键字:有效性 输入 检查      更新时间:2023-10-16

假设从文本文档中读取以名称、空格和十进制值形式写入的信息。例如,文件中的一行可能包含:

老虎

56.3

我需要做的是验证第一部分是一个只包含字母的字符串,第二部分只包含包含小数的数字。到目前为止,我有以下基本代码:

ifstream input("data.txt");
while(!input.eof())
{
    string name;
    double score;
    input >> name;
    input >> score;
}

我该怎么做呢

您可能想看看新的C++11正则表达式。它们是专门为输入验证之类的任务而设计的。

检查字符串是否只包含数字和+-符号的最小示例如下:

#include <iostream>
#include <regex>
#include <string>
int main()
{
    std::string testString;
    std::regex integer("(\+|-)?[[:digit:]]+");
    input >> testString;
    if(std::regex_match(input, integer))
        std::cout << "Valid number" << std::endl;
    else
    {
        std::cout << "No valid number" << std::endl;
    }
}

然而,你需要一个非常最新的编译器(GCC 4.9我认为),使用它们。如果您无法使用,可以使用Boost Regex Library,它提供了一个非常类似的接口。

将数据读取为字符串并从那里解析:

std::string name, score_str;
while (input >> name >> score_str)
{
    if (!is_alphabetic(name) || !is_decimal_number(score_str)) {
        // error
    }
    else {
        // convert score_str to a double and assign it to score
    }
}

下面是is_alphabetic的一个例子:

template<class iter>
bool is_alphabetic(iter beg, iter end)
{
     bool found_number = true;
     while (beg != end && (found_number = !std::isdigit(*beg++)))
        ;
     return found_number;
}
template<class container>
bool is_alphabetic(container& c)
{
    return is_alphabetic(c.begin(), c.end());
}
#include<iostream>
#include<string>
using namespace std;
int validate(string,string);
int main(){
    string s;
    string d;
    cin>>s>>d;
    if(validate(s,d)) cout<<"ok";
    else cout<<"not ok";

}

int validate(string s, string d){

    for(int i=0;i<s.size();++i){
            //all either small letter or capital letter else error
        if(!((s[i]>='A' && s[i]<='Z') || (s[i]>='a' && s[i]<='z'))){ 
            return 0;
        }
    }
    int f=0;
    for(int i=0;i<d.size();++i){
            //either digits or decimal
        if(!((d[i]>='0' && d[i]<='9') || d[i]=='.')){
            return 0;
        }
            //if decimal already present and again decimal its an error ex. 123.23.23
        if(d[i]=='.' && f==1) return 0;
            //flag indicating decimal present
        if(d[i]=='.') f=1;
        if(d[i]>='0' && d[i]<='9' && f==1) f=2; // validate decimal like 132. (not valid)
    }
    if(f==1) return 0;
    return 1;
}

最简单的代码是:

while(!input.eof())
{
    string name;
    string score;
    input >> name;
    for (int i=0; i<name.size() ; i++) {
        if ( ( name [i] >= 'A' && name [i] <= 'Z' ) || ( name [i] >= 'a' && name [i] <= 'z' ) || (name [i] == '_') ) {
            continue;
        } else {
            cout <<"Name is not valid!";
            break;
        }
    }
    input >> score;
    for (int j=0; j<score.size() ; j++) {
        if ((score [j] >= '0' && score [j] <= '9') || (score[j]=='.') ) {
            continue;
        } else {
            cout <<"Number is not valid!";
            break;
        }
    }
}