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;
}
-
(2 points.) In no more than three sentences, why is it necessary to pass
&n, and notnitself, toscanf? -
(3 points.) Does this implementation of
get_intprevent 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;
}
-
(2 points.) Unfortunately, this implementation often triggers segmentation faults. In no more than three sentences, why?
-
(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();
}
-
(2 points.) Propose, in no more than three sentences and/or in pseudocode, how you could use
getcharto implementget_stringin such a way that it’s not vulnerable to segmentation faults. Note that CS50’s implementation ofget_stringuses a similar function,fgetcon line 130 ofcs50.c. -
(2 points.) In no more than three sentences, why is it safer to use
getchar(orfgetc) than to usescanfto implementget_string?