Homework??? Already???

Once there was a string… now there is an integer.

int AscToInt(const char *num)
{
int newnum=0;
int i=0;
int neg=1;
if(num[0]==’-‘)
{
neg=-1;
i++;
}
for(i; i<20; newnum = newnum*10+(num[i]-48), i++)
{
if(num[i]<47 || num[i]>58)
{
if(num[i]!=NULL)
newnum = 0;
break;
}
}
return newnum*neg;
}

if you want to try it out, put it in this program:

#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
char num[20];
printf(“Please enter a number: “);
scanf (“%s”, &num);
printf(“%d\n”, AscToInt(num));
return 0;
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s