Write a program that reads a string of characters and interprets it as a positive integer in the decimal base. For the conversion, use the functions of <ctype.h> and the alphabetic precedence of the characters from '0' to '9'. Save the result in a variable of type long. The conversion stops when the first character does not represent a decimal digit. Use an OK logical indicator that specifies whether the string correctly represents an integer and positive value.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
void main()
{
/* Declarations */
char CH[100]; /* numerical string to convert */
long N; /* numerical result */
int I; /* counter */
int OK; /* logical flag indicating whether the */
/* string was converted successfully */
/* Reading */
printf("Enter a positive integer number : ");
gets(CH);
/* Conversion of the string */
OK = 1;
N = 0;
for (I = 0; OK && CH[I]; I++)
if (isdigit(CH[I]))
N = N * 10 + (CH[I] - '0');
else
OK = 0;
/* dislay */
if (OK)
printf("Numerical Value : %ld\n", N);
else
printf("\a\"%s\" does not represent a correct "
"positive integer number.\n", CH);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Checking if a number is even using bit manipulation