Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert string to number

Status
Not open for further replies.

youngun

Programmer
Apr 27, 2001
61
US
Hi, Please help me with the following problem, thank you very much.

I know how to use atoi or strtod to convert string to number, however, if the number cannot be converted, the functions returns zero, what if the number is already 0, then I can't tell if that means it can't be converted or it's converted to 0

if I have a string "0.3.4" (it's meant to have only one numeric value in the string), which is not a valid number, how can I check that it is not a valid number?
thank you so much
 
#include <iostream>
#include <cctype>

using namespace std;

#define MAX_VALUE 7
#define DECIMAL '.'

bool Check_Zero( char *sString );
bool Valid_Num ( char *sString );


int main()
{
char sValue[MAX_VALUE];
int iValue = 0;

while ( true )
{
cout << &quot;Enter an integer value from ( 0 to 32,767) &quot;
<< &quot;with a MAX of 5 digits: &quot;;
cin.getline( sValue,MAX_VALUE );

if ( Check_Zero( sValue ) )
{
iValue = 0;
break;
}
else if ( Valid_Num( sValue ) )
{
iValue = atoi( sValue );
break;
}
else
cout << endl
<< &quot;Invalid int.&quot;
<< endl;
}

cout << &quot;Your Int value: &quot; << iValue;

return 0;

}

bool Check_Zero( char *sString )
{
if ( sString[0] == '0' && sString[1] == '\0' )
return true;

return false;
}

bool Valid_Num( char *sString )
{
int iDecimal = 0;
int iCounter = 0;
char cBuffer = -1;

while( cBuffer != '\0' )
{
cBuffer = sString[iCounter++];

if ( cBuffer == DECIMAL )
{
if( ++iDecimal == 2 )
{
cout << endl
<< &quot;Too many decimals...&quot;;
return false;
}
}
else if ( ( !isdigit( cBuffer ) ) &&
cBuffer != '\0' )
return false;
}

return true;

}

Of course you may get a wrong result if the user enters more then 5 digits, but you can always add code to remedy this. Mike L.G.
mlg400@blazemail.com
 

there are a couple more things you could do such as implimenting strstr to make sure the string consists of numbers and decimal points (negative sign???)

then, check for multiple decimal places using strstr ex:

char* ret = strstr(sValue,&quot;.&quot;);
ret = strstr(ret+1,&quot;.&quot;);

if(ret)// multiple decimals, bad number

also using strstr could be useful

int len = strstr(sValue,&quot;1234567890.-&quot;);
if(len != strlen(sValue)// invalid number


Hope these 2 lil' tid bits helped

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top