简体   繁体   中英

C Program exits before taking input from user

Why does my program close before taking the input for k and then displaying it.

I am writing a code for a menu based program so I need to take input from user after he has entered the information so I can have 1.Print names 2.Exit while doing this I realized my program didn't take the input and just skipped the part where it is supposed to take value of l from user. So trying to debug it I deleted stuff and came down to this simple program and realized it still wont work any idea why?

#include <stdio.h>

struct student
{
    char name[50];
    char lname[50];
    float marks;
} s[15];

int main ()
{
    int i, j,k;

    printf("Please enter the number of students:\n");
    scanf ("%d", &j);

    printf ("Please enter the information for students as asked.\n");

    for (i = 0; i < j; i++)
    {
        scanf ("%s %s %f\n", s[i].name, s[i].lname, &s[i].marks);
    }

    printf("Please enter a number\n");
    scanf ("%d", &k);

    printf("your number was %d", k);

    return 0; 
}

scanf ("%s %s %f\\n", s[i].name, s[i].lname, &s[i].marks);

should be

scanf ("%s %s %f", s[i].name, s[i].lname, &s[i].marks);

The \\n in scanf just consumes newline char. It will continue consuming newline until a non-newline char is found, which is put back into stdin for the next IO operation

Try this Code

#include<stdio.h>
typedef struct student
{
char name[50];
char lname[50];
int mark;
}S;

int main ()
{
int i, j,k;

printf("Please enter the number of students:\n");
scanf ("%d", &j);

S record[j];

for (i = 0; i < j; i++)    {
   printf ("Please enter the information for %d student as asked.\n",i+1);

  scanf ("%s %s %f",record[i].name, record[i].lname, &record[i].mark);
}

printf("Please enter a number\n");
scanf ("%d", &k);

printf("your number was %d \n", k);

return 0;
}

You were declaring structure student array in the structure declaration itself.you have to declare the array in main function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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