Write a program that will take a number in string format and convert it and print it in integer format. For e.g.,

Input String => ”574”
Output Integer => 574

#include <stdio.h>

#include <string.h>

#include <math.h>

#include <ctype.h>

void read_string(char sample[]);

int check_string(char sample[]);

void convert_int(char sample[]);

int main()

{

int status;

char sample[100];

read_string(sample);

status = check_string(sample);

while ( status == 1 )

{

printf("\nYou are supposed to enter only digits[0-9]\n");

read_string(sample);

status = check_string(sample);

}

convert_int(sample);

return 0;

}



/*This function reads the number entered by the user and stores it in the character array sample. We are using fflush to flush the input buffer so that subsequent scans provide the desired input */

void read_string(char sample[])

{

printf(“\nEnter the string to be converted to integer(only numbers) :”);

strcpy(sample, “”);

gets(sample);

fflush(stdin);

}

/* This function ensures that the string consists of digits only. If it contains other characters such as punctuation characters, alphabets etc. then it returns 1 ( Error )

*/

int check_string(char sample[]) {

int i, flag = 0;

for ( i = 0; i<strlen(sample)-1; i++) {

if( isdigit( sample[i] )) {

flag = 1;

}

else {

flag = 0;

break;

}

}

if ( flag == 0 ) {

return 1;

}

else {

return 0;

}

}

/* This function does the conversion of the number in string format to integer format. A character when used in expressions is treated as an integer and the ASCII value of the character is used in the expression. For e.g., if the character is ‘4’ then ASCII value of 4 is 0x34 which is decimal 52. If we want the integer 4 then we subtract the 48 from the ASCII value of 4 expressed in decimal form, i.e., 52 – 48 = 4

*/

/* pow function is used to calculate exponent and you have to include math.h and separately link the math library as shown ( Unix/Linux )

$ gcc convert.c -lm

*/

void convert_int(char sample[]) {

int i, sum = 0, j = 0;

for ( i=strlen(sample)-1; i>=0; i– ) {

sum = sum + (sample[i] – 48)*pow(10, j);

j++;

}

printf(“The converted integer = %d\n”, sum);

}