fgets 函数的问题
Problems with fgets function
这里我使用 fgets() 获取用户输入的几个字符串,它从未出现在输出中:
#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;
}
不要混用 scanf()
和 fgets()
或如手册页所述:
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.
这是一个 fgets()
版本:
#include <stdio.h>
#include <string.h>
#define LEN 20
char *strip(char *s) {
size_t n = strlen(s);
if(n && s[n-1] == '\n') s[n-1] = '[=10=]';
return s;
}
int main() {
char color[LEN];
char pluraNoun[LEN];
char celebrity[LEN];
printf("Enter a color: ");
fgets(color, LEN, stdin);
printf("Enter a plural noun: ");
fgets(pluraNoun, LEN, stdin);
printf("Enter a celebrity: ");
fgets(celebrity, LEN, stdin);
printf("Roses are %s\n", strip(color));
printf("%s are blue\n", strip(pluraNoun));
printf("I love %s\n", strip(celebrity));
return 0;
}
您想检查 fgets()
的 return 值以确保您的程序在 EOF
.
上做一些合理的事情
这里我使用 fgets() 获取用户输入的几个字符串,它从未出现在输出中:
#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;
}
不要混用 scanf()
和 fgets()
或如手册页所述:
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.
这是一个 fgets()
版本:
#include <stdio.h>
#include <string.h>
#define LEN 20
char *strip(char *s) {
size_t n = strlen(s);
if(n && s[n-1] == '\n') s[n-1] = '[=10=]';
return s;
}
int main() {
char color[LEN];
char pluraNoun[LEN];
char celebrity[LEN];
printf("Enter a color: ");
fgets(color, LEN, stdin);
printf("Enter a plural noun: ");
fgets(pluraNoun, LEN, stdin);
printf("Enter a celebrity: ");
fgets(celebrity, LEN, stdin);
printf("Roses are %s\n", strip(color));
printf("%s are blue\n", strip(pluraNoun));
printf("I love %s\n", strip(celebrity));
return 0;
}
您想检查 fgets()
的 return 值以确保您的程序在 EOF
.