在进行另一个 scanf 后会跳过字符串的 scanf

问题描述 投票:0回答:1

这是一个程序,它接受用户的输入,即:卷号、姓名以及他的物理、化学和数学分数并打印它们。

如果

%[^\n]s
用于获取字符串输入,则在此程序中不起作用。

这个程序运行良好

#include <stdio.h>
#include <string.h>

void main()
{
    int roll_no;
    char student[1000];
    float physics, maths, chemistry;
    printf("Enter your roll no. : ");
    scanf("%d", &roll_no);
    fflush(stdin);
    printf("\nEnter your name : ");
    fflush(stdin);
    scanf("%s", student);
    fflush(stdin);
    printf("\nEnter your physics : ");
    scanf("%f", &physics);
    printf("\nEnter your maths : ");
    scanf("%f", &maths);
    printf("\nEnter your chemistry : ");
    scanf("%f", &chemistry);
    
    printf("Student's Name : %s\nPhysics Marks : %.2f Chemistry Marks : %.2f Maths Marks : %.2f",
           student, physics, chemistry, maths);
}

为了获取学生的全名(名字和姓氏),我后来用

scanf("%[^\n]s", student);
代替了
scanf("%s", student);

当我使用

%[^\n]s
作为学生数组时,程序采用卷号。用户的输入然后会跳过学生
scanf
。直接跳转到物理
scanf
进行物理评分。
fflush(stdin)
也被用来防止
scanf
在获取多种数据类型时出现故障,但它似乎仍然不起作用

arrays c string input scanf
1个回答
0
投票

您的问题中有多个问题和误解:

  • 没有

    %[^\n]s
    转换规范,尾随
    s
    不是转换的一部分,它充当必须与输入字符匹配的字符
    s
    ,这不会发生,因为
    %[^\n]
    仅在换行符或文件末尾。

  • fflush(stdin)
    具有未定义的行为。它不会“刷新”输入流。您可以使用循环读取并丢弃输入行中的剩余字符,包括换行符: int c; while ((c = getchar()) != EOF && c !+ '\n') continue;

  • %s

    %[^\n]
    之间的区别在于空白字符的行为:
    %s
    忽略前导空白,包括换行符,然后读取字符并将其存储到目标数组中,直到读取空白并将其推回到输入中溪流。相反,
    %[^\n]
    读取并存储除换行符之外的任何字符,换行符会被推回。
    
    

© www.soinside.com 2019 - 2024. All rights reserved.