Reputation: 69
My programs goal: Only the letters will be printed out nothing else. The program will continue until the return is received at which time the sum of the digits will be printed on the next line. Use getch not getchar... It's suppose to only print the uppercase letter. I'm just gonna fail it because no one would ever use getch() :(
example user input: What was entered: a9 wF23’;/4i
What gets printed: What the line actually shows: aA9wWFiI
The sum of the digits is: 18
I'm curious as to why I am getting an echo? It prints out the letter entered 3 times. Now I suppose if both my if's are true it would print twice?...
***Update thanks for the input everyone I will update in the morning. Out of caffine :(
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int digitconversion (int sum, int c);
int caseconversion (int c);
int main(int argc, char *argv[])
{
char c;
int sum = 0;
printf("Please enter a character or characters ");
c = getch();
while (c !='\r') {
c = getch();
if (c >= '0' && c <= '9')
digitconversion (sum, c);
if (c >= 'A' && c <= 'Z')
putchar(c);
if (c >= 'a' && c <= 'z')
{
putchar(c);
c = caseconversion (c);
putchar(c);
}
c = getch();
}
printf("The sum of the digits is %d\n", sum);
return 0;
}
int caseconversion (int c)
{ char u;
u = c - (char)32;
return u;
}
//function converts letter to number
int digitconversion (int sum, int c)
{
sum += (int)(c - '0');
return sum;
}
Upvotes: 1
Views: 103
Reputation: 41036
Please, use standard functions to illustrate an example (getchar
instead of getch
).
There are a lot of bugs in your code:
while (c !='\r') {
must be
while (c !='\n') {
if (c >= 'A' && c >= 'Z')
must be
if (c >= 'A' && c <= 'Z')
digitconversion (sum, c);
must be
sum = digitconversion (sum, c);
You are using 3 calls to getch
(one is enough)
You are including ctype.h
but using your own functions, why? Use toupper(c)
and isdigit(c)
.
This code works:
#include <stdio.h>
int digitconversion(int c);
int caseconversion(int c);
int main(void)
{
int c, sum = 0;
printf("Please enter a character or characters ");
while ((c = getchar()) != '\n' && c != EOF) {
if (c >= '0' && c <= '9')
sum += digitconversion(c);
if (c >= 'A' && c <= 'Z')
putchar(c);
if (c >= 'a' && c <= 'z') {
c = caseconversion(c);
putchar(c);
}
}
printf("\nThe sum of the digits is %d\n", sum);
return 0;
}
int caseconversion(int c)
{
return c - 32; /* This is not true under EBCDIC encoding, use toupper() */
}
int digitconversion(int c)
{
return c - '0';
}
Output:
Please enter a character or characters abc1234ABC
ABCABC
The sum of the digits is 10
Upvotes: 3