John Batistë
John Batistë

Reputation: 45

Unable to enter Name with Spaces in C program?

This program asks for employee name, age and Salary. There is one slight problem and i don't know what this wrong. When i enter name without space or just the first name, then program works correctly but as soon as i enter full name with space. The program just skips some values without asking and jumps to other values. I know their is something wrong with scant of "worker[i].name" and i have tried %c too but with no success.

struct employee {

int pAge;
float salary;
char name[30];
};

int main(void) {

struct employee worker[2];

for (int i = 0; i < 2; i++) {

    printf("Enter Name of %d employee: ", (i+1));
    scanf(" %s", worker[i].name);

    printf("Enter Age of %d employee: ", (i+1));
    scanf("%d", &worker[i].pAge);

    printf("Enter Salary of %d employee: ", (i+1));
    scanf("%f", &worker[i].salary);
}
printf("\n");

printf("List of All workers\n\n");
printf( "Age\tSalary\t\tName\n");

for (int i = 0; i < 2; i++) {
    printf("%d\t%.2f\t\t%s\n", worker[i].pAge, worker[i].salary, worker[i].name);
    }
}

Upvotes: 2

Views: 2341

Answers (1)

Mansoor Akram
Mansoor Akram

Reputation: 2056

Its very simple just use this instead:

scanf(" %[^\n]s", worker[i].name);

Upvotes: 1

Related Questions