For pset1 I want to reject an empty user input, so that when the user presses 'enter', either the Mario code runs or it gives the user an error message.

Pseudo code:

  1. printf ('message to input 1-23');
  2. scansf ('%i', &height);

  3. if (input <= 23 && input > 0)

{ ... a do/while (with 2 nested for) runs mario if input is 1-23. }

  1. else

{ printf ("prints error message if input isn't 1-23");}

This rejects numbers outside the range and all characters, but not empty spaces. I reckon there's an elegant solution to this (can fgets work? How?), but advice would be helpful at this point.

Question: How do I reject an empty user input?


Use GetInt() from the cs50 library!

GetInt(), as its name suggests, waits for an int input from the user and returns it.

You may use like that:

#include <cs50.h>
#include <stdio.h>

int main(void)
    // prompt the user for an int
    printf("Please give me an int:");
    int i = GetInt();

    printf("Thanks for the %d", i);
  • Thanks, Kareem. How would I implement that? And isn't it a bit problematic to rely on the cs50 library? I mean, it teaches us to solve the problem, but only within the cs50 application.
    – Fredrik
    Jun 15 '14 at 12:00
  • @Fredrik, Sorry! Messed things up 'cause I was on my phone! I was saying you don't need to implement nor to compile it. It's already written an compiled for you on the appliance! I just edited my answer with a sample code to show you how you can use it.
    – kzidane
    Jun 15 '14 at 12:15
  • Hmm. When I write it that way it gives me the following error: GetInt.c:(.text+0x16): undefined reference to 'GetInt' collect2: error: ld returned 1 exit status. Know what the problem is?
    – Fredrik
    Jun 15 '14 at 12:36
  • How are you compiling your program?
    – kzidane
    Jun 15 '14 at 12:37
  • gcc mario.c -o mario Should I use make instead?
    – Fredrik
    Jun 15 '14 at 12:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .