没有为名字输入值时如何使循环中断

How to make for loop break when no value entered for first name

我无法让我的代码在名字处中断,它只会在我将所有值留空后中断。

#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] != '[=10=]') {
            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 . . .

首先,您的 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;
}