In: Electrical Engineering
In C program. Read and convert a sequence of digits to its equivalent integer. Any leading white space should be skipped. The conversion should include digit characters until a non-digit character is encountered. Modify the program so it can read and convert a sequence of digit characters preceded by a sign, + or -.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char string1[100], string2[100];
printf("Enter the string of digits with numbers ::
");
scanf("%s", string1);
int i, stringLen, num = 0, j;
stringLen = strlen(string1);
for(i = 0, j = 0; i < stringLen; i++) {
if (isspace(string1[i])) {
}
else if (isdigit(string1[i]))
{
string2[j] = string1[i];
j++;
}
else
break;
}
num = atoi (string2);
printf ("The string value in digit is = %d",
num);
}
/******************** OUTPUT OF PROGRAM
***********************
Enter the string of digits with numbers ::
502414
The string value in digit is = 502414
**************************************************************/
// Modified for + or - sign
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char string1[100], string2[100];
printf("Enter the string of digits with numbers ::
");
scanf("%s", string1);
int i, stringLen, num = 0, posflag = 0, j;
stringLen = strlen(string1);
for(i = 0, j = 0; i < stringLen; i++) {
if (isspace(string1[i])) {
}
else if (string1[i] == '-')
{
posflag++;
}
else if (isdigit(string1[i]))
{
string2[j] = string1[i];
j++;
}
}
num = atoi (string2);
num = posflag ? (num * (-1)) : num;
printf ("The string value in digit is = %d",
num);
}
/******************* OUTPUT OF PROGRAM
*************************
Enter the string of digits with numbers
:: +102654
The string value in digit is = 102654
Enter the string of digits with numbers
:: -512415
The string value in digit is = -512415
***************************************************************/