Here I use fgets() to get user input with several strings, it never appeared in the output:
#include <stdio.h>
int main() {
char color[20];
char pluraNoun[20];
char celebrity[20];
printf("Enter a color: ");
scanf("%s", color);
printf("Enter a plural noun: ");
scanf("%s", pluraNoun);
printf("Enter a celebrity: ");
fgets(celebrity, 20, stdin);
printf("Roses are %s\n", color);
printf("%s are blue\n", pluraNoun);
printf("I love %s\n", celebrity);
return 0;
}
CodePudding user response:
scanf()
with a specified width for string is same as fgets()
, but fgets()
reads a extra character namely newline, which adds extra code to remove them.
I would suggest you to keep using scanf()
with width for strings.
Some Points
- Initialize your character arrays using
= { };
- Always check whether
scanf()
was successful or not - Make sure those character arrays have an extra space for null terminating character
'\0'
Final Code
#include <stdio.h>
int main() {
char color[21] = {};
char pluraNoun[21] = {};
char celebrity[21] = {};
printf("Enter a color: ");
if (scanf(" s", color) != 1) {
fputs("bad input", stderr);
}
printf("Enter a plural noun: ");
if (scanf(" s", pluraNoun) != 1) {
fputs("bad input", stderr);
}
printf("Enter a celebrity: ");
if (scanf(" s", celebrity) != 1) {
fputs("bad input", stderr);
}
printf("Roses are %s\n", color);
printf("%s are blue\n", pluraNoun);
printf("I love %s\n", celebrity);
return 0;
}
CodePudding user response:
Don't mix scanf()
and fgets()
or as man page says:
It is not advisable to mix calls to input functions from the stdio library with low-level calls to read(2) for the file descriptor associated with the input stream; the results will be undefined and very probably not what you want.
Here is a fgets()
version:
#include <stdio.h>
#include <string.h>
#define LEN 20
void strip(char *s) {
size_t n = strlen(s);
if(n && s[n-1] == '\n') s[n-1] = '\0';
}
int main() {
char color[LEN];
char pluraNoun[LEN];
char celebrity[LEN];
printf("Enter a color: ");
fgets(color, LEN, stdin);
strip(color);
printf("Enter a plural noun: ");
fgets(pluraNoun, LEN, stdin);
strip(pluraNoun);
printf("Enter a celebrity: ");
fgets(celebrity, LEN, stdin);
printf("Roses are %s\n", color);
printf("%s are blue\n", pluraNoun);
printf("I love %s\n", celebrity);
return 0;
}
I left it out to not change your program too much, but check the return value from fgets()
if you want to ensure your program does something sensible if on EOF
.