Write a C program to convert string to integer without using atoi.
#include <stdio.h>
#include <string.h>
int main() {
char string[16];
int num = 0, i;
/* enter your input string */
printf("Enter your input string:");
fgets(string, 16, stdin);
string[strlen(string) - 1] = '\0';
/* check whether i/p has digits alone */
for (i = 0; i < strlen(string); i++) {
if (string[i] < '0' || string[i] > '9') {
printf("Wrong input!!\n");
return 0;
}
}
i = 0;
/* converting string to number */
while (string[i] != '\0') {
num = num * 10 + (string[i] - '0');
i++;
}
/* print the result */
printf("Integer value: %d\n", num);
return 0;
}
#include <string.h>
int main() {
char string[16];
int num = 0, i;
/* enter your input string */
printf("Enter your input string:");
fgets(string, 16, stdin);
string[strlen(string) - 1] = '\0';
/* check whether i/p has digits alone */
for (i = 0; i < strlen(string); i++) {
if (string[i] < '0' || string[i] > '9') {
printf("Wrong input!!\n");
return 0;
}
}
i = 0;
/* converting string to number */
while (string[i] != '\0') {
num = num * 10 + (string[i] - '0');
i++;
}
/* print the result */
printf("Integer value: %d\n", num);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input string:12345667
Integer value: 12345667
Enter your input string:12345667
Integer value: 12345667
No comments:
Post a Comment