我的程序运行正常,除非我为其中一个数字输入一个数字,然后它才会终止而不是声明无效的卡号。如何使用isdigit来处理问题?
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
//Input Variables
double cardnumber;
string name;
string address;
double TypeofBook;
string Title;
float RegularFine;
float BestSellersFine;
float MagazinesFine;
float HardcoverBooksFine;
double DaysLate;
char Choice;
char Y;
char N;
char y;
char n;
do
{ //Get Patron's info
cout << "Please Enter Patron's Library Card Number: \n";
cin >> cardnumber;
//Validate card number
while ((cardnumber <= 0) ||(cardnumber > 9999))
{
cout << "You have entered an invalid card number \n";
cout << "Enter a valid card number \n";
cin >> cardnumber;
}
答案 0 :(得分:1)
bool isnum(const std::string& arg){
for(std::string::iterator it=arg.begin();it!=arg.end();it++)
if(!isdigit(*it))
return false;
return true;
}
答案 1 :(得分:0)
isdigit用于char。如果您希望将非数字字符作为输入。你必须使用字符串来获取那些然后验证。如下:
string cardnumber;
cout << "Please Enter Patron's Library Card Number: \n";
cin >> cardnumber;
//Validate card number
while (cardnumber.find_first_not_of("0123456789") != -1)
{
cout << "You have entered an invalid card number \n";
cout << "Enter a valid card number \n";
cin >> cardnumber;
}
祝你好运,
答案 2 :(得分:0)
使用std::cin >> cardnumber
表达式的返回值:
int cardnumber;
if (std::cin >> cardnumber && (cardnumber > 0 && cardnumber < 9999)) {
// success
}
其中“成功”表示已成功从int
检索std::cin
并且它在区间<0; 9999)
答案 3 :(得分:0)
#include <iostream>
#include<string>
using namespace std;
int toNumber(string s)
{
int num=0;
for (int i=0;i<s.size();i++)
if (s[i]>='0'&&s[i]<='9')
num = num*10 + s[i]-'0';
else
return -1;
return num;
}
int main(int argc, const char * argv[])
{
int number;
string cardnumber;
cout << "Please Enter Patron's Library Card Number: \n";
cin >> cardnumber;
while ( (number = toNumber(cardnumber)) == -1 || number > 9999) // no need to check if less than zero. cause it will return -1.
{
cout << "You have entered an invalid card number \n";
cout << "Enter a valid card number \n";
cin >> cardnumber;
}
// use card number here as string (cardnumber) and int (number).
cout << cardnumber << " " << number << endl;
return 0;
}
答案 4 :(得分:0)
我猜你正在寻找一个不应该输入char
的验证,如果我是正确的,那么有一个函数is_int
read this,