Getting Input

Recall that CS50’s implementation of get_int prompts the user for an int. If the user inputs anything other than an int (or a value that cannot fit in an int), the function prompts the user again.

Consider the below implementation of get_int instead, which calls scanf.

#include <stdio.h>

int get_int(char *prompt)
{
    int n;
    do
    {
        printf("%s", prompt);
        scanf("%i", &n);
    }
    while (n > 2147483647);
    return n;
}
  1. (2 points.) In no more than three sentences, why is it necessary to pass &n, and not n itself, to scanf?

  2. (3 points.) Does this implementation of get_int prevent integer overflow? In no more than three sentences, why or why not?


Recall that CS50’s implementation of get_string prompts the user for a string (of any length), otherwise known as a char *.

Consider the below implementation of get_string instead, which also calls scanf, which can be compiled in CS50 IDE with clang (but not make, which diagnoses some problems for you).

#include <stdio.h>

char *get_string(char *prompt)
{
    printf("%s", prompt);
    char *s;
    scanf("%s", s);
    return s;
}
  1. (2 points.) Unfortunately, this implementation often triggers segmentation faults. In no more than three sentences, why?

  2. (2 points.) In no more than three sentences, why is it possible to prevent some, but not necessarily all, of those segmentation faults?


Recall that CS50’s implementation of get_char prompts the user for a char. If the user’s input is not a single char, the function prompts the user again.

Consider the below implementation of get_char instead, which calls getchar, a (similarly named) function declared in stdio.h.

#include <stdio.h>

char get_char(char *prompt)
{
    printf("%s", prompt);
    return getchar();
}
  1. (2 points.) Propose, in no more than three sentences and/or in pseudocode, how you could use getchar to implement get_string in such a way that it’s not vulnerable to segmentation faults. Note that CS50’s implementation of get_string uses a similar function, fgetc on line 130 of cs50.c.

  2. (2 points.) In no more than three sentences, why is it safer to use getchar (or fgetc) than to use scanf to implement get_string?