Reputation:
I'm doing intro to C and I need to write a program that prompts the user to enter in characters, an equal sign, and an integer. I need to use getchar()
until the '='
then scanf()
for the integer. The program should then output only the integer back to the user.
Right now it prints out unnecessary code re the location for every character input, then at the end outputs the correct integer. This is the code I have:
#include <stdio.h>
#define EQUAL '='
int main(void)
{
char ch;
int integer = 0;
printf("Enter some text, an equal sign and an integer:\n");
while ((ch = getchar())!= '\n') //while not end of line
{
if (ch == EQUAL){
scanf("%d", &integer);
}
printf("The integer you entered is: %d\n", integer);
}
return 0;
}
I can't find an example and need clarification on how to fix the issue.
Upvotes: 0
Views: 454
Reputation: 165396
You got bit by a gotcha in C. The problem is this:
if( ch == EQUAL )
scanf("%d", &integer);
printf("The integer you entered is %d\n", integer);
if
with no braces will only include the single statement following it. That code is really this:
if( ch == EQUAL ) {
scanf("%d", &integer);
}
printf("The integer you entered is %d\n", integer);
To avoid this gotcha, I would recommend two things:
gcc supports a warning about this, -Wmisleading-indentation
.
For more gotchas like this read "C Traps And Pitaflls" by Andrew Koenig.
Upvotes: 4