繁体   English   中英

如何使用 fgets() 和 sscanf

[英]How to use fgets() and sscanf

假设有一种情况:需要输入:

Name of Player
Height of Player
Age of Player

用户可以输入这样一种方式,即他可以在每次输入后按enter(\n)

printf("Please enter Name, Height and Age of Player");

我只想通过fgets()sscanf()的组合来获取这个输入

您可以定义一个为您执行此操作的函数:

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 :将保存您的输入的char缓冲区。
  • sizeline的大小(容量)。
  • stream :您要从中读取的文件流。

如果读取的字符数超过缓冲区的容量,则必须刷新输入缓冲区:

int flush_stdin(void)
{
    int c = 0;
    while ((c = getchar()) != EOF && c != '\n');
    return c;
}

至于sscanf() ,用它来解析fgets()读取的内容。

这是一个演示:

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.

笔记:

  • 永远不要使用fflush(stdin)
  • 为简单起见,跳过检查readline()返回值。

暂无
暂无

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

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