>what is code like this saying:
Code:
while ((ch = getchar()) != '\n')
{
......
}
The ch = getchar() means "read one character from the stdin and assign this value to the int ch". Since this expression is parenthesized, it evaluates ch and compares it to the newline character, "if the character just read from the stdin was not a newline, perform the statements enclosed in braces". Or, "if the character just read from the stdin was a newline, break out of the while loop.
>How does it work?
Code:
get_first()
{
int ch;
/* Read a character from the stdin, assign its value to 'ch'. */
ch = getchar();
/*
* Read a character from the stdin. If it is a newline, break out of the loop.
* Otherwise, discard it value (don't assign it to anything).
*/
while (getchar() != '\n')
continue;
return ch;
}
[edit]
>3) The program is then supposed to start over once you've added or subtracted, asking for two integers again, but it does not do this and simply starts over at the part where it asks if you want to add or subtract. How can I fix this?
Put the calls to get_int() in the loop.
[/edit]
[edit too]
This may be closer to what you want.
Code:
#include <stdio.h>
int newline(void)
{
int c = getchar();
while ( getchar() != '\n' )
continue;
return c;
}
int get_int(void)
{
int num;
printf("Please enter an integer:\n");
scanf("%d", &num);
return num;
}
int get_choice(void)
{
int ch;
printf("Please choose either of the following actions:\n");
printf("a. add s. subtract\n");
ch = newline();
while ( ch != 'a' && ch != 's' )
{
printf("Invalid answer. Please choose a or s:\n");
ch = newline();
}
return ch;
}
int add(int num1, int num2)
{
int total = num1 + num2;
printf("%d + %d = %d\n", num1, num2, total);
return total;
}
int sub(int num1, int num2)
{
int total = num1 - num2;
printf("%d - %d = %d\n", num1, num2, total);
return total;
}
int main(void)
{
int n, m, ch;
while ( (ch = get_choice()) != 'q' )
{
n = get_int();
m = get_int();
switch ( ch )
{
case 'a': add(n, m); break;
case 's': sub(n, m); break;
default : printf("That is invalid. Try again.\n");
}
}
return 0;
}
[/edit]
[edit yet again]
Problems with scanf.
Another FAQ.
An FAQ with more details about obtaining a number from user input.
[/edit]