检查输入有效性
Checking for Input Validity?
假设从文本文档中读取以名称、空格和十进制值形式写入的信息。例如,文件中的一行可能包含:
老虎 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;
}
}
}
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何从 Python 扩展检查输入变量的有效性
- 使用正则表达式检查输入的有效性
- QLineEdit with QValidator:不管输入的有效性如何,对编辑完成做出反应
- 读取输入数据并检查其有效性的通用宏
- 检查输入有效性