This has been puzzling me all this week. This is actually a homework
assignment
from last semesmter. But the teacher wouldn't tell us why certain
things didn't work, but it didn't just work. My thing was what
actually turn this while loop into an endless loop instead of waiting
for user response it'll would skip right over it. Could someone with
the time explain this to me what would make it behave like this
int main() {
char again = 'Y';
Aside from your inconsistent and sometimes odd layout, which makes
your code hard(er) to read, so I suggest you work on that:
while (again != 'N')
{
printf("\nEnter degree type: (B for Bachelors), (M for Masters), (D
for Doctorate\n");
printf("\t\t\t: ");
scanf("%1c", °ree);
printf("\nEnter number of years of work experience: ");
scanf("%2d",&wk_exp);
printf("\nEnter current Pay: ");
scanf("%5d",&p_pay);
printf("\nWant to do this again? Press N for NO: ");
/*scanf("%1c", &again); */
getchar();
This reads a character but doesn't do anything with it, in particular
it doesn't store to 'again', so the loop continues. You probably meant
again = getchar();
But once you do that, or if you do the scanf("%1c",&again) instead --
or it could be just %c, 1 is the default width for that specifier --
you will find that the loop _always_ exits because the character you
read is the newline (or perhaps other garbage character) following the
pay value, because the scanf %d above reads only through the end of
the number leaving any other input, in particular the newline,
buffered for later reads. This is (almost) 12.18 in the FAQ, in the
usual places and at
http://www.eskimo.com/~scs/C-faq/top.html .
scanf has other "features" that can be problematical as well, (many)
also detailed in that part of the FAQ. Especially if you fail to check
its return value, as you did.
The way of doing input usually recommended here is to read each line
into a buffer with fgets(), and then pick the desired data value(s)
out of it with sscanf() (note the addtional s -- that's scan formatted
_from string_) or sometimes explicit code and/or other functions like
strto
l[l](), strtok(), strchr(), str[c]spn(), etc. Even that isn't
perfect, if you (might) get input lines longer than your fixed-size
buffer, but that gets into complications I suggest you leave aside for
now and come back to later when you are a little more experienced.
- David.Thompson1 at worldnet.att.net