2017-02-17 36 views
0

Я пишу код, который позволяет пользователю вводить информацию для двух человек, однако, если пользователь пытается добавить другого сотрудника, когда массив уже содержит информацию для 2 сотрудников, должно появиться сообщение об ошибке. На данный момент код, похоже, просто перезаписывает информацию сотрудника, а не выводит сообщение об ошибке.Проверка целостности структуры массива

Кроме того, в качестве кода в настоящее время вы должны ввести оба набора данных сотрудника перед тем, как появится меню. Есть ли способ получить его, чтобы вы вводили набор данных о сотрудниках, а затем появляется меню? Вот мой код:

#include <stdio.h> 

#define SIZE 2 
// Define Number of Employees "SIZE" to be 2 

struct Employee{ 
    int ID; 
    int AGE; 
    double SALARY; 
}; 
//Declare Struct Employee 


/* main program */ 
int main(void) { 

    int option = 0; 
    int i; 
    struct Employee emp[SIZE]; 

    printf("---=== EMPLOYEE DATA ===---\n\n"); 

    // Declare a struct Employee array "emp" with SIZE elements 
    // and initialize all elements to zero 

    do { 
      // Print the option list 
      printf("\n"); 
      printf("1. Display Employee Information\n"); 
      printf("2. Add Employee\n"); 
      printf("0. Exit\n\n"); 
      printf("Please select from the above options: "); 

      // Capture input to option variable 
      scanf("%d",&option); 
      printf("\n"); 

      switch (option) { 
        case 0: // Exit the program 
          printf("Exiting Employee Data Program. Goodbye!!!\n"); 

          break; 
        case 1: // Display Employee Data 
          // @IN-LAB 

          printf("EMP ID EMP AGE EMP SALARY\n"); 
          printf("====== ======= ==========\n"); 

          //Use "%6d%9d%11.21f" formatting in a 
          //printf statement to display 
          //employee id, age and salary of 
          //all employees using a loop construct 

          for(i=0; i<SIZE; i++) { 
            printf("%d %d %11.2lf", emp[i].ID, emp[i].AGE, emp[i].SALARY); 
} 

          //The loop construct will be run for SIZE times 
          //and will only display Employee data 
          //where the EmployeeID is > 0 

          break; 
        case 2: //Adding Employee 
            // @IN-LAB 

          printf("Adding Employee\n"); 
          printf("===============\n"); 

          if (emp[i].ID > emp[SIZE]) { 
            printf("Full"); 
          } 

          for(i=0;i>SIZE;i++) { 
            printf("Error"); 
          } 

          for(i=0;i<SIZE;i++) { 

          printf("\nEnter employee ID: "); 
          scanf ("%d", &emp[i].ID); 

          printf("\nEnter employee Age: "); 
          scanf ("%d", &emp[i].AGE); 

          printf("\nEnter employee Salary: "); 
          scanf ("%11lf", &emp[i].SALARY); 
            } 


          //Check for limits on the array and add employee 
          //data accordingly 

          break; 

        default: 

          printf("ERROR: Incorrect Option: Try Again\n\n"); 

      } 

    } while (option!= 0); 

    return 0; 

} 
+2

Пожалуйста, прочтите [Как отлаживать небольшие программы (от Eric Липпертого)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). SO не является отладочной службой. Когда вы идентифицируете проблему с логикой вашей программы, если определенное поведение вашего кода по-прежнему оставляет вас в недоумении, тогда обязательно опубликуйте вопрос. – StoryTeller

+0

Спасибо за это, не знал, что что-то подобное существует. Я обязательно буду использовать его, когда буду сталкиваться с проблемами в будущем. – Jinto

ответ

1

Я добавил переменную петлю, которая используется, чтобы оставить петлю while, когда пользователь вводит 0 в качестве опции.
Добавлена ​​другая переменная number_of_employees, чтобы отслеживать количество сотрудников. Он инициализируется 0 & при каждом добавлении нового пользователя.

int option = 0; 
int i; 
int loop = 1; /* This variable is used to terminate the programme by exiting the while loop */ 
int number_of_employees = 0; /* We add this variable that increments every time a new employee is added */ 
struct Employee emp[SIZE]; 

printf("---=== EMPLOYEE DATA ===---\n\n"); 

// Declare a struct Employee array "emp" with SIZE elements 
// and initialize all elements to zero 

while(loop) { 
     // Print the option list 
     printf("\n"); 
     printf("1. Display Employee Information\n"); 
     printf("2. Add Employee\n"); 
     printf("0. Exit\n\n"); 
     printf("Please select from the above options: "); 

     // Capture input to option variable 
     scanf("%d",&option); 
     printf("\n"); 

     switch (option) { 
       case 0: // Exit the program 
         printf("Exiting Employee Data Program. Goodbye!!!\n"); 
         loop = 0; // Exiting 
       break; 

       case 1: // Display Employee Data 
         // @IN-LAB 

         printf("EMP ID EMP AGE EMP SALARY\n"); 
         printf("====== ======= ==========\n"); 

         //Use "%6d%9d%11.21f" formatting in a 
         //printf statement to display 
         //employee id, age and salary of 
         //all employees using a loop construct 

         for(i=0; i<SIZE; i++) { 
           printf("%d %d %11.2lf", emp[i].ID, emp[i].AGE, emp[i].SALARY); 
         } 

         //The loop construct will be run for SIZE times 
         //and will only display Employee data 
         //where the EmployeeID is > 0 

       break; 

       case 2: //Adding Employee 
           // @IN-LAB 

         printf("Adding Employee\n"); 
         printf("===============\n"); 

         /* This is how to check if we can add an employee */ 
         if (number_of_employees < size) { 

         printf("\nEnter employee ID: "); 
         scanf ("%d", &emp[number_of_employees].ID); 

         printf("\nEnter employee Age: "); 
         scanf ("%d", &emp[number_of_employees].AGE); 

         printf("\nEnter employee Salary: "); 
         scanf ("%11lf", &emp[number_of_employees].SALARY); 

         /* Inceremeting */ 
         number_of_employees++; 
         } 

         else { 
         printf("Full"); 
         } 

         //Check for limits on the array and add employee 
         //data accordingly 

       break; 

       default: 

         printf("ERROR: Incorrect Option: Try Again\n\n"); 

     } 
} 
1

Вы можете отлаживать с помощью обычных операторов printf(), по крайней мере для этого кода. сравнение проверить полный имеет вопросы, как почему вы сравните int с struct типа здесь if (emp[i].ID > emp[SIZE])

Я хотел бы предложить следующее:

Инициализировать ваше целое с 0 значение:

int i = 0; 

использовать другой счетчик предположим j для отображения содержимого массива, чтобы вы сохранили значение i

for(int j = 0;j<SIZE;j++) { 
    printf("%d %d %11.2lf\n", emp[j].ID, emp[j].AGE, emp[j].SALARY); 
} 

Проверка с я для полноты

if(i >= SIZE) { 
    printf("Full"); 
    break; 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^