Prevent buffer overflow by passing the maximum number of characters to scanf
and skip the '\n'
with a dummy format:
#include <stdio.h>
int main(void) {
char word1[20], word2[20];
printf("Enter word 1: ");
fflush(stdout); // make sure prompt is output
if (scanf("%19[^\n]%*c", word1) < 1)
return 1;
printf("Enter word 2: ");
fflush(stdout); // make sure prompt is output
if (scanf("%19[^\n]%*c", word2) < 1)
return 1;
return 0;
}
Note that using scanf
to read lines has some side effects: you cannot read an empty line this way and you have to hard code the buffer size in the format string in an awkward way.
I would instead suggest using fgets()
and stripping the trailing '\n'
this way:
#include <stdio.h>
#include <string.h>
int main(void) {
char word1[20], word2[20];
printf("enter word 1 : ");
fflush(stdout); // make sure prompt is output
if (fgets(word1, sizeof word1, stdin) == NULL)
return 1;
word1[strcspn(word1, "\n")] = '\0'; // strip the \n if any
printf("enter word 2 : ");
fflush(stdout); // make sure prompt is output
if (fgets(word2, sizeof word2, stdin) == NULL)
return 1;
word2[strcspn(word2, "\n")] = '\0'; // strip the \n if any
printf("word1: |%s|, word2: |%s|\n", word1, word2);
return 0;
}