Commit f04addfa authored by Hans Buchmann's avatar Hans Buchmann

to:string->unsigned

parent 8ea3d396
......@@ -185,17 +185,49 @@ void String::to(unsigned v,char s[])
bool String::to(char s[],unsigned* val)
{
//123
//|
//s=dec+ at least one decimal digit
//state machine
unsigned i=0; //index in s
unsigned state=0;
unsigned v=0; //number
while(true)
{
char ch=s[i++];
switch(state)
{
case 0:
{
auto d=isDecDigit(ch);
if (d<0)
{
//a234
return false;
}
v=d;
state=1;
}
break;
case 1:
{
if (ch=='\0')
{
//1\0
*val=v; //by reference
return true;
}
auto d=isDecDigit(ch);
if (d<0)
{
//111x
return false;
}
v=10*v+d;
//remain in state 1
}
break;
//etc
}
}
......@@ -205,28 +237,16 @@ bool String::to(char s[],unsigned* val)
//test
int main(int argc,char** args)
{
unsigned v=123;
char s[30]; //defined *not* initialized
String::to(v,s);
/*
unsigned
+------------+
v | 123|
+------------+
+-----------------------------------------------------------+
s |x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|
+-----------------------------------------------------------+
x:dont care
String::to(v,s)
decimal
+------------------------------------------------------------+
s |1|2|3|\0|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|x|
+------------------------------------------------------------+
|--terminating zero
*/
std::cout<<"s="<<s<<"\n";
char s[]="123";
unsigned v=0;
auto res=String::to(s,&v);
if (res)
{
std::cout<<"v="<<v<<"\n";
}
else
{
std::cout<<s<<" is not a decimal number\n";
}
return 0;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment