devika
devika

Reputation: 1

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 ....

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

Upvotes: 0

Views: 8885

Answers (3)

Plamen Nikolov
Plamen Nikolov

Reputation: 4187

what about

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

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

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754420

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.

Upvotes: 1

user418748
user418748

Reputation:

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.

Upvotes: 1

Related Questions