I am trying to read in a string that may or may not include spaces ex. "hello world". By doing the following with a number select menu that is inputted by the user. This is just a small replica of what I am trying to do.
#include <stdio.h>
#include <string.h>
int main(void){
char line[3][80];
strcpy(line[0],"default line 1\n");
strcpy(line[1],"default line 2\n");
strcpy(line[2],"default line 3\n");
for(int i = 0; i < 3; i++){
printf("%s", line[i]);
}
int option = 0;
printf("would you like to replace line 1? (1 for yes)\n");
scanf("%d",&option);
if(option==1){
printf("what would you like to replace the line with?\n");
fgets(line[0],strlen(line[0]),stdin);
}
for(int i = 0; i < 3; i++){
printf("%s", line[i]);
}
}
Why is it that after I enter 1 to change the line, it prints the statement asking what I want to replace it with and will automatically enter nothing then printing the strings with the first one as empty?
I also have already tried reading the line with sscanf("%[^\n\t]s", line[0]);
without any luck. Any ideas?
It's because
leaves the
\n
character in stdin and is consumed by the first call tofgets()
. That's why it's best to avoidscanf()
in C completely.You can fix it with:
But I'd suggest using
fgets()
to readoption
as well and then you can usestrtol()
to convert it into an integer.Note that this statement is not probably what you intended (which limits what you can read into
line[0]
).You probably meant to use:
so that you can read upto the actual size of
line[0]
.Please read the C Faq entry as well: http://c-faq.com/stdio/scanfprobs.html
Using
fgets()
generally seems less error-prone than tangling withscanf()
, but if the user enters a string that is as long as or longer than the maximum number of characters specified, any extra characters up to and including the newline remain in the input stream. For this reason I usually write my own version ofgets()
to get input strings from the user, and if I want numeric input I usestrtol()
. Here is an example of such a function:Applied to the OPs problem, I might do something like this:
Your problem is that the
'\n'
char is left intostdin
and consumed byfgets
.I'd suggest you to always use
fgets
for read inputs, so