First time working with C and I was asked to do a simple average function WITHOUT scanf (only using getchar) for my Systems class. I ended up writing an unnecessarily complicated loop just to get my code to compile and even after compiling+running it doesn’t seem to do anything after taking in the keyboard input.
#include <stdio.h>
#include <stdlib.h>
//average program
//use getchar to get numbers separately instead of scanf and integers.
//Not sure why. Most likely to build character.
int main (int argc, const char * argv[])
{
char x,z;
float avg;
int tot,n,b;
printf("Input Integer values from 1 to 100. Separate each value by a space. For example: 23 100 99 1 76\n");
ret:
x=getchar();
while( x != '\n' );
{
if(x==isspace(x))
{ goto ret;}
opd:
z=getchar();
if ((z == isspace(z)))
{
b = x - '0';//subtracting 0 from any char digit returns integer value
tot +=b;
n++;
goto ret;
}
else if(z == '\n')
{
b = x - '0';
tot +=b;
n++;
goto end;
}
else
{
x = x*10;
x = x + z;
goto opd;
}
}
end:
avg=tot/n;
printf("Taking of the average of the values. The average is %1.2f\n",avg);
return avg;
}
while(...);causes an infinite loop, it’s the same as saying:while(...) continue;getchar()… it’s too confusing with multiplegetchar()calls and your code is trying to throw away the first line the way it’s written.gotostatement, your instructor won’t like them and they are quite unnecessary. (Do read up on break and continue.)getchar()directly, it’s useful to be able push a character back on the input stream. Seeman 3 ungetcor just write a simple wrapper aroundgetchar().You should only need one character of pushback at the end of a parser loop.