String Verification (Checks if string has certain characters or not)
Mar 13, 2012 at 1:13am UTC
So, I'm trying to make a program to convert numbers between bases and I'm stuck on number verification, where it checks the string for only the digits 0-9 and/or letters A-F. But, when I enter something like "19s", it just skips telling me the error message I want. Any solutions for a rewrite?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Number Base Converter Version 1.00" << endl;
cout << "Enter a number you want to convert: " ;
string number;
cin >> number;
int i = 0, status = 0;
while (status = 0) {
for (int i = 0; i < number.length(); i++) {
if (number.at(i) != '0' || '1' || '2' || '3' || '4' || '5' || '6' || '7' || '8' || '9' || 'A' || 'a' || 'B' || 'b' || 'C' || 'c' || 'D' || 'd' || 'E' || 'e' || 'F' ) {
cout << "The number you enter must only contain the digits 0-9 and/or letters A-F." << endl;
cout << "Enter a number you want to convert: " ;
cin >> number;
status = 0;
} else {
status = 1;
}
}
}
Mar 13, 2012 at 2:47am UTC
if ( x != '0' || '2' )
evaluates to
if ( (x!='0' ) || '2)'
In the case where x is '0':
if ( ('0' !='0' ) || '2' )
which becomes:
if ( false || '2' )
and since '2' is non-zero and is always true, the control expression is also always true.
The correct way to write your if would be :
1 2
char c = number.at(i) ;
if ( c != '0' && c != '1' && c != '2' && c != '3' /* ... */ )
You might want to try something along the lines of:
1 2 3 4 5 6 7 8 9
#include <algorithm>
bool is_hex_digit(char c )
{
static const char digits[] = "0123456789ABCDEFabcdef" ;
static const char * digits_end = digits + (sizeof (digits) / sizeof (digits[0])) ;
return digits_end != std::find(digits, digits_end, c) ;
}
Or a switch construct may be more to your taste.
Last edited on Mar 13, 2012 at 2:51am UTC
Topic archived. No new replies allowed.