C program to convert string to integer: It is frequently required to convert a string to an integer in applications. String should consists of digits only and an optional '-' (minus) sign at beginning for integers. For string containing other characters we can stop conversion as soon as a non digit character is encountered but in our program we will handle ideal case when only valid characters are present in string. Library function atoi can be used to convert string to an integer but we will create our own function.
C programming code
#include <stdio.h>
#include<conio.h>
int toString(char []);
void main()
{
char a[100];
int n;
clrscr();
printf("Input a valid string to convert to integer\n");
scanf("%s", a);
n = toString(a);
printf("String = %s\nInteger = %d\n", a, n);
getch();
}
int toString(char a[])
{
int c, sign, offset, n;
if (a[0] == '-')
{
sign = -1;
}
if (sign == -1)
{
offset = 1;
}
else
{
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++)
{
n = n * 10 + a[c] - '0';
}
if (sign == -1)
{
n = -n;
}
return n;
}
}
No comments:
Post a Comment