(Beginner) Convert String to Number

Postby Admin on Sun Jan 21, 2001 10:58 pm

About every few weeks, there is a post on our board about this question.
To make it obvious, here is the official answer to this popular question.

There are two ways to do this.

First, the easy way.
<pre id=code><font face=courier size=2 id=code>
string s; int i;
s = "12345";
i = (int) s;
</font id=code></pre id=code>


Second, the hard way:
You can write a routine that convert a string into a number.
<pre id=code><font face=courier size=2 id=code>

strToInt(string sStr)
{
int iIndex, iValue, iResult;
int iLen;

iResult = 0;
iLen = strlen(sStr);

for( iIndex=0; iIndex < iLen;iIndex++)
{
iValue = (int)strgetc(sStr, iIndex) - '0';
iResult = iResult * 10 + iValue;
}
return iResult;
}

main()
{
int i;
i = strToInt("10245");
putsl(i);
showconsole();

}
</font id=code></pre id=code>
Admin
 
Posts: 86
Joined: Fri Oct 06, 2000 6:00 am
Location: USA

Return to PocketC for CE KB

Who is online

Users browsing this forum: No registered users and 2 guests

cron