2017-04-09 23 views
0

我無法讓我的代碼在名字中被打破,它只會在我將所有值留空後纔會中斷。如何爲沒有輸入名字的值創建循環中斷

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


void main(void) { //Start main function 

    // Declare variables 
    char charTempArray[50] = ""; 
    char charFirstNames[50][50]; 
    char charLastNames[50][50]; 
    char charTempSal[10] = ""; 
    int intSalaries[50]; 
    int intSalarySum = 0; 
    int intSalaryAvg = 0; 
    int intSalaryTop = 0; 
    int intSalaryBot = 9999999999; 
    int intArraySize = 0; 
    int i = 0; 
    int intCharConv = 0; 

    //User input to build the arrays 
    for(i = 0; i < 50; ++i) 
     if (charFirstNames[i - 1][0] != '\0') { 
      printf("Please enter Employees first name.\n "); 
      gets(charTempArray); 
      strcpy(charFirstNames[i], charTempArray); 
      printf("Please enter Employees last name.\n "); 
      gets(charTempArray); 
      strcpy(charLastNames[i], charTempArray); 
      printf("Please enter Employees salary.\n "); 
      gets(charTempSal); 
      intCharConv = atoi(charTempSal); 
      intSalaries[i] = intCharConv; 
      intArraySize = i; 
     } 
     else { 
      break; 
     } 

這裏是輸出。

所有的
Please enter Employees first name. 
test 
Please enter Employees last name. 
me 
Please enter Employees salary. 
100 
Please enter Employees first name. 

Please enter Employees last name. 

Please enter Employees salary. 

Teacher 1: test me  Salary(per year):100 

The average salary is:100 per year 
The top salary is 100 
The bottom salary is 100 
Press any key to continue . . . 

回答

1

首先,你if將嘗試數組的邊界時i=0外部訪問的元素。其次,你應該測試空的名字,你得到的第一個名字之後:

for(i = 0; i < 50; ++i) 
{ 
    printf("Please enter Employees first name.\n "); 
    gets(charTempArray); 
    strcpy(charFirstNames[i], charTempArray); 
    if(charTempArray[0] == 0) 
     break; 
    printf("Please enter Employees last name.\n "); 
    gets(charTempArray); 
    strcpy(charLastNames[i], charTempArray); 
    printf("Please enter Employees salary.\n "); 
    gets(charTempSal); 
    intCharConv = atoi(charTempSal); 
    intSalaries[i] = intCharConv; 
    intArraySize = i; 
} 
+0

我曾經試過,但我忘了振奮的for循環,有一個循環外的休息,因此沒有工作。謝謝。 –

相關問題