简体   繁体   中英

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

它非常简单,只需使用以下代码即可:

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

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