can't input string with space in c structure

74 views Asked by At

I wanted to write a program to generate student mark list. But in this one, i can only insert first part of the name. the rest is skipped. i looked most forums about this problem and it still happens. help if you can.

// mark list using struct

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

struct mlist { char name[30]; int cs; int maths; int eng; int total; float perc; };

void main() { int n, i;
printf("How many Students? : ");
scanf("%d", &n);

struct mlist std[n];
struct mlist *ptr = std;

printf("Marks out of 100");

for (i = 0; i < n; i++)
{
    printf("\n\nEnter details of Student %d ==>\n", i + 1);
    printf("Enter Name : ");
    scanf("%s", ptr->name);
    printf("Enter Computer Science Marks : ");
    scanf("%d", &ptr->cs);
    printf("Enter Mathematics Marks : ");
    scanf("%d", &ptr->maths);
    printf("Enter English Marks : ");
    scanf("%d", &ptr->eng);
    ptr++;
}

ptr = std;
for (i = 0; i < n; i++)
{
    printf("\n---------------------------------\n");
    printf("Name : %s\n", ptr->name);
    printf("Computer Science : %d\n", ptr->cs);
    printf("Mathematics : %d\n", ptr->maths);
    printf("English : %d\n", ptr->eng);
    ptr->total = ptr->cs + ptr->maths + ptr->eng;
    ptr->perc = (float)ptr->total / 300 * 100;
    printf("Total %d with %.2f%%\n", ptr->total, ptr->perc);
    ptr++;
}
}
1

There are 1 answers

2
Allan Wind On

scanf("%s", ...) reads a word. Here are some options to read a line instead:

  1. scanf("%42[^\n]", s); where s is an array of characters of 42 characters. Always include a maximum field width (here 42) when reading strings with scanf() and friends.

  2. fgets(s, sizeof s, stdin);.

  3. getline();. is another option if your struct contains a char pointer opposed to array. It will then dynamically allocate space for the array.

fgets() and getline() will include the '\n' so you may need to remove it with s[strcspn(s, "\n")] = '\0';.