[英]How to use fgets() and sscanf
Suppose there is a case: input required:假设有一种情况:需要输入:
Name of Player
Height of Player
Age of Player
User may input in such a way that he may press enter(\n)
after each input.用户可以输入这样一种方式,即他可以在每次输入后按
enter(\n)
。
printf("Please enter Name, Height and Age of Player");
All I want to take this input with the combination of fgets()
and sscanf()
我只想通过
fgets()
和sscanf()
的组合来获取这个输入
You can define a function that does that for you:您可以定义一个为您执行此操作的函数:
bool readline(char *line, size_t size, FILE *stream)
{
if (!fgets(line, size, stream))
return false;
size_t npos = strcspn(line, "\n");
if (line[npos] != '\n') {
flush_stdin();
return false;
}
line[npos] = '\0';
return true;
}
line
: the char
buffer that will hold your input. line
:将保存您的输入的char
缓冲区。size
: the size (capacity) of line
. size
: line
的大小(容量)。stream
: the file stream you want to read from. stream
:您要从中读取的文件流。 In case the number of characters read exceeds the capacity of the buffer, one must flush the input buffer:如果读取的字符数超过缓冲区的容量,则必须刷新输入缓冲区:
int flush_stdin(void)
{
int c = 0;
while ((c = getchar()) != EOF && c != '\n');
return c;
}
As for sscanf()
, use it to parse what has been read by fgets()
.至于
sscanf()
,用它来解析fgets()
读取的内容。
Here is a demo:这是一个演示:
int main(void)
{
char input[64], name[64];
printf("Enter your name: ");
readline(name, sizeof(name), stdin);
printf("Enter your height: ");
readline(input, sizeof(input), stdin);
float height = .0;
if (sscanf(input, "%f", &height) != 1) {
printf("Input error\n");
return 1;
}
printf("Enter your age: ");
readline(input, sizeof(input), stdin);
int age = 0;
if (sscanf(input, "%d", &age) != 1) {
printf("Input error\n");
return 1;
}
printf("%s is %d years old and %.2f feet tall.\n", name, age, height);
}
Enter your name: Johnny
Enter your height: 5.6
Enter your age: 18
Johnny is 18 years old and 5.60 feet tall.
Notes:笔记:
fflush(stdin)
.fflush(stdin)
。readline()
return values for simplicity.readline()
返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.