C Programming Problem

Manakore

New Member
I have to write a program that allows the user to enter in characters in the keyboard until # is executed. At this point the program will post results.

The number of alphabetical letters
The number of spaces
The number of digits
The sum of digits

The problem is, I have no idea how to get the program to count the sum of digits properly. Since I am entering characters, the number is not registered as an integer so when it adds the sum, the result is incorrect. Any help will be much appreciated. Thanks!

#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <limits.h>

int main(void)
{
char character;
int num_alpha = 0;
int num_spaces = 0;
int num_digits = 0;
int sum_digits = 0;
int num_min = INT_MIN;
int num_max = INT_MAX;
int a = 0;

while((character = getchar()) != '#')
{
putchar(character);
if(isalpha(character))
num_alpha+=1;
else if(character == ' ')
num_spaces+=1;
else if(character == '\t' || character == '\n' || character == '#')
num_alpha+=0;
else
{
sum_digits +=character;
num_digits++;
}
}


printf("\n");
printf("The number of alphabetical characters is %d.\n",num_alpha);
printf("The number of spaces is %d.\n",num_spaces);
printf("The number of digits is %d.\n",num_digits);
printf("The sum of the digits is %d.\n",sum_digits);


return 0;
}
 
Code:
atoi(&someChar); //Converts a char to an int

Be sure to put an if statement or something with it so it only tries to convert numbers.
 
That actually deals with strings though, which unfortunately we haven't learned yet and thus I cannot use it. Is there any other way to go about this problem?
 
That actually deals with strings though, which unfortunately we haven't learned yet and thus I cannot use it. Is there any other way to go about this problem?

It should work for a char. A string in C is nothing more than an array of char's either way.

I may be mistaken, though. It's been a while since I've used C.

Supposedly, this will also work:

int x = myChar - '0';
 
Supposedly, this will also work:

int x = myChar - '0';
Yes that will also work. Assuming your entered number is a single digit (in which in this case it will be). However, you'll have to be careful, chars can be treated as integers very easily in C and something like 'a' - '0' will execute.
 
It should work for a char. A string in C is nothing more than an array of char's either way.

I may be mistaken, though. It's been a while since I've used C.

Supposedly, this will also work:

int x = myChar - '0';

This worked thanks a lot sir!
 
Back
Top