开发者

scanning a string using structure

this below is the c code for the structure. in this program while scaning the value of name program is terminating from that point. and also it takes 2 values as name array. its not giving any runtime error or warning. can u tell me what is the proper solution for this program on my email id .开发者_如何学JAVA...

#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;
}


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

Any reason you include the : and whitespaces in the format string?

Read here : http://www.cplusplus.com/reference/clibrary/cstdio/scanf/

Try all of them again but without the :. Eg. scanf("%d",&st.id);

Keep in mind that scanf("%s",st.name); can end up overwriting memory it should not.


You should be checking the return status from the scanf() calls, so you can tell which one is failing.

  • Are you remembering to add the colons to the input data that your format strings require?

Remember, anything that isn't white space or a conversion specifier in a scanf() format is expected in the input, and you are seeking colons after numbers and names.

Also, if you plan to enter both first and last name, the %s specifier is not appropriate; it stops at the first space.


what about

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

When enter the name do not use spaces. to get the name with spaces use fgets(..)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜