looping a program that converts to uppercase and shifts 4 letter grades in C -
this program calls 2 functions uppercase(), converts input uppercase, , shift(), shifts grade input.
here's uppercase() function:
void uppercase(char *p) { if(islower(*p)) { *p = toupper(*p); } }
here's shift() function:
void shift(char *p1, char *p2, char *p3, char *p4) { int count = 0; { ++count; char tmp; tmp = *p4; *p4 = *p3; *p3 = *p2; *p2 = *p1; *p1 = tmp; printf("grades shifted #%i: %c %c %c %c \n", count, *p1, *p2, *p3, *p4); } while (count < 4); }
here's main function.
#include <stdio.h> #include <ctype.h> main (void) { float choice; { char c1, c2, c3, c4; printf ("enter 4 letter grades find statistics: "); scanf("%c %c %c %c", &c1, &c2, &c3, &c4); getchar(); uppercase(&c1); uppercase(&c2); uppercase(&c3); uppercase(&c4); printf("input grades: %c %c %c %c\n", c1, c2, c3, c4); shift(&c1, &c2, &c3, &c4); printf("want shift more grades (y/n)? "); choice = getchar(); } while ( choice == 'y' || choice == 'y'); getchar(); }
my output looks this
enter 4 letter grades find statistics: abcd
input grades: b c d
grades shifted #1: d b c
grades shifted #2: c d b
grades shifted #3: b c d a
grades shifted #4: b c d
want shift more grades (y/n)? y
enter 4 letter grades find statistics: adff
input grades:
d f
grades shifted #1: f
d
grades shifted #2: d f
a
grades shifted #3: d f
grades shifted #4:
d f
want shift more grades (y/n)?
the format gets messed on second input, , when input y after second input, program closes. i've been tinkering past hour , can't figure out why formatting gets messed or why loop closes/crashes on third attempt.
also how can make main function accepts inputs of a-d or f.
thanks.
i think it's because have new line sitting in getchar() input
when enter 'y' press enter, you're getting "y\n".
clear input when re-entering while loop
printf("want shift more grades (y/n)? "); choice = getchar(); c = getchar(); while (c != '\n' && c != eof) c = getchar(); } while ( choice == 'y' || choice == 'y');
for second question:
you need check values of c1,c2,c3,c4 luckily there's function that
while( !(isalpha(c1) && isalpha(c2) && isalpha(c3) && isalpha(c4)) ) printf ("enter 4 letter grades find statistics: "); scanf("%c %c %c %c", &c1, &c2, &c3, &c4); getchar();
note isalpha function checks value of each character... here's ascii table, notice a-z , a-z are. http://www.asciitable.com/
scanf/getchar() line clearing: http://www.velocityreviews.com/forums/t318260-peek-at-stdin-flush-stdin.html
Comments
Post a Comment