Apr 12, 2015 at 9:42am UTC
Write your question here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
bool f2(char * str)
{
if (!*str)
return true ;
if (*str>'0' ||*str<'9' )
return false ;
return f2(str+1);
}
how it cheks if the string is build only from digits???
Last edited on Apr 12, 2015 at 9:44am UTC
Apr 12, 2015 at 9:47am UTC
OK i get it because its ||
like de morgane.
Apr 12, 2015 at 10:21am UTC
yeh thanks man..but its a part from a test they wanted to make it complex..
look at my other topic about files
Last edited on Apr 12, 2015 at 10:22am UTC
Apr 12, 2015 at 1:34pm UTC
So is this problem of yours solved?
yeh thanks man..but its a part from a test they wanted to make it complex..
What does that have to do with your question?
Last edited on Apr 12, 2015 at 1:34pm UTC
Apr 12, 2015 at 10:03pm UTC
if the 0-termination is reached try to write *str == 0 because it's easier to understand at first sight :)
becuase you wrote that ^
Apr 12, 2015 at 10:36pm UTC
The function doesn't work. Line 10 makes it return false for every non-empty string input.
if (*str>'0' ||*str<'9' )
Picture a number line. All values are either >0 or <9.
Fix by replacing with
if (*str>'9' ||*str<'0' )// false if outside the range 0-9
Demo:
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 26 27 28 29 30 31
#include<iostream>
using std::cout;
// original (except for const qualifier)
bool f2(const char * str)
{
if (!*str) return true ;
if (*str>'0' ||*str<'9' ) return false ;// wrong
return f2(str+1);
}
// corrected
bool f3(const char * str)
{
if (!*str) return true ;
if (*str>'9' ||*str<'0' ) return false ;// right
return f3(str+1);
}
int main ()
{
const char * a = "123" ;
cout << "a " << ( f2(a) ? " is" : " is not" ) << " a number.\n" ;// it isn't
cout << "a " << ( f3(a) ? " is" : " is not" ) << " a number.\n" ;// yes, it is
const char * b = "1b3" ;
cout << "b " << ( f3(b) ? " is" : " is not" ) << " a number.\n" ;// no, it isn't
cout << '\n' ;
return 0;
}
Last edited on Apr 12, 2015 at 10:42pm UTC
Apr 13, 2015 at 6:16am UTC
its not wrong it goes like de morgan rules!!!!!!!
(*str>'0'||*str<'9')
(*str>'0'&&*str<'9')
theres a diffrence...
Apr 14, 2015 at 11:58pm UTC
Test the function. It doesn't work.
It will return false for everything but an empty string = "".