使用结构扫描字符串

时间:2011-07-13 12:49:19

标签: c

以下是结构的c代码。在这个程序中,扫描名称程序的值是从那一点终止。并且它还需要2个值作为名称数组。它没有给出任何运行时错误或警告。你可以告诉我在我的电子邮件地址....

上该程序的正确解决方案是什么
#include<stdio.h>
#include<conio.h>
struct student
{
    int id;
    char name[20];
    float per;
} st;
main()
{
    clrscr();
    printf("\nenter the info of student");
    printf("\n=======================\n");
    printf("id:");
    scanf("%d:",&st.id);
    printf("name :");
    scanf("%s :",st.name);
    printf("per :");
    scanf("%f :",&st.per);

    printf("\n id is: %d \n",st.id )  ;
    printf("\n name is: %s \n",st.name )  ;
    printf("\n per is: %1f \n",st.per )  ;
    getch();
    return 0;
}

3 个答案:

答案 0 :(得分:1)

scanf("%d:",&st.id); scanf("%s :",st.name); scanf("%f :",&st.per);

您是否在格式字符串中包含:whitespaces

请在此处阅读:http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

再次尝试所有这些但没有:。例如。 scanf("%d",&st.id);

请记住,scanf("%s",st.name);最终可能会覆盖不应该写入的内存。

答案 1 :(得分:1)

您应该检查scanf()来电的退货状态,以便了解哪一方失败。

  • 您是否记得将冒号添加到格式字符串所需的输入数据中?

请记住,输入中需要任何非空格或scanf()格式的转换说明符,并且您在数字和名称后搜索冒号。

此外,如果您计划同时输入名字和姓氏,则%s说明符不合适;它停在第一个空间。

答案 2 :(得分:0)

scanf("%s",st.name);

输入名称时请勿使用空格。 使用空格获取名称使用fgets(..)