0

I have the following code:

#include<stdio.h>
#include "commonf.h" //So, this is the way you include from a directory?
void main(){
    println("Welcome to Number Guesser v 0.1 ");
    println("Think of a number between 0 and 100 (and please, make it an integer!)");
    println("Legend: Y=Yes B=Bigger than that S= Smaller than that");
    int guessed=0;
    float curnum=100.0;
    char cursign='?';
    while(cursign!='y'){
        if(cursign=='?' || cursign=='s'){
            curnum=curnum/2;
        }
        else if(cursign=='b'){
            curnum=curnum+curnum/2;
        }
        else{
            printf("You are wrong. Stop it. %c .  TEESST",cursign);
        }
        char askstring[4096];
        sprintf(askstring,"%s%f%s","Is your number ",curnum," ? (y/b/s)");
        println(askstring);
        scanf("%c",&cursign); //Scanf has to expect a new line for some reason.
    }
}

(I pasted all of it, since I am a c noob)

If the code looks like this, the loop will execute twice per user input, once with cursign= to whatever the user entered, and once with it equal to \n.

If I change the scanf line to

scanf("%c\n",&cursign);

It asks for the first input twice, then works as a charm. What's the problem, and what should I do?

alk
  • 69,737
  • 10
  • 105
  • 255

1 Answers1

3

Change this scanf("%c\n",&cursign); to this scanf(" %c",&cursign);. This will eat up the trailing newline character.

Also as per standard main should return an int (even though this is not the reason for your problem). According to C standards main should be int main(void) or int main(int argc, char* argv[])

When you enter a character like y and hit the ENTER key, a character (which you entered) and a character (which is the enter keystroke - the newline character) gets placed in the input buffer. The first character gets consumed by the scanf but the newline remains in the input buffer so what happens is that the next time you enter something there 3 characters newlinechar + 'y' + newlinechar. So that makes scanf behave funny.

This is a great link from Grijesh - C Printf and Scanf Reference

Sadique
  • 22,572
  • 7
  • 65
  • 91