简体   繁体   English

如何使用 fgets() 和 sscanf

[英]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 . sizeline的大小(容量)。
  • 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:笔记:

  • Never use fflush(stdin) .永远不要使用fflush(stdin)
  • Skipped checking for readline() return values for simplicity.为简单起见,跳过检查readline()返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM