简体   繁体   中英

Storing values in struct objects using c and a do-while loop

I'm trying to store a few values in a struct object and I want to repeat the prompt until the user types in "yes". I want to use a do-while loop for that. I'm already failing with the read-in of the first "last name". When I type in something, the program just stops (no error). I don't even use the do-while, since I'm not sure if it will work with my while() condition.

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

struct employeelist 
{
 char last[6];
 char first[6];
 int pnumber;
 int salary;
};

int main()

{
 struct employeelist employee[5]; 
 char check; 

 //do
 //{
 printf("Hello. Please type in the last name, the first name, the personal number and the salary of your employees.\n");
 printf("Last name: ");
 scanf("%c", employee[1].last);  

 printf("First name: ");
 scanf("%c", employee[1].first);  

 printf("Personal number: ");
 scanf("%d", &employee[1].pnumber);  

 printf("Salary: ");
 scanf("%d", &employee[1].salary);  

 printf("You have more employess (yes/no)?: ");
 scanf("%c", &check);  
 //}while (scanf("yes"));

 return 0;
}

Use %s as your format specifier if you're trying to get a string. You might also want to limit its length to 5, since that's how much space you have for last and first . So that would be %5s . Also, 5 characters is pretty short for a name.

Another comment: arrays in C are zero-based, so employee[1] is the second employeelist in your array. If you want to do this in a loop with an incrementing index, start at 0.

Hi when you read char array you must use scanf("%s", employee[1].last); %s but not %c

What do you think this code does?

scanf("%c", ....

%c indicates that scanf should only read ONE character.
One letter is not going to get you an entire name.

You need to switch to %s for starters.

  1. First of all the first index to work with will be '0',not 1.
  2. wrong identifier for string,it should be %s.
  3. If you just want to iterate by asking y/n then just change the display message from yes/no to y/n and also change that strange while condition to check=='y'||check=='Y'.
  4. The code will actually not work after 5 iterations because you initialized only 5 structures of that type.Why don't you add that in the loop?

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