Using fgets()
usually seems less error prone than obfuscating with scanf()
, but if the user enters a string longer than or exceeding the maximum number of specified characters, any additional characters before and including newline remain in the input stream. For this reason, I usually write my own version of gets()
to get input strings from the user, and if I want to use numerical input, I use strtol()
. Here is an example of such a function:
char * s_gets(char *st, int n) { char *ret; int ch; ret = fgets(st, n, stdin); if (ret) { while (*st != '\n' && *st != '\0') ++st; if (*st) *st = '\0'; else { while ((ch = getchar()) != '\n' && ch != EOF) continue;
In relation to the OPs problem, I can do something like this:
#include <stdlib.h> // for strtol() ... char buf[80]; int option = 0; printf("would you like to replace line 1? (1 for yes)\n"); s_gets(buf, sizeof(buf)); option = strtol(buf, NULL, 10); if(option==1){ printf("what would you like to replace the line with?\n"); s_gets(line[0],sizeof(line[0])); }
source share