gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:58:28 25 4
gpt4 key购买 nike

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

#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 . . .

最佳答案

首先,当 i=0 时,您的 if 将尝试访问数组边界之外的元素。其次,您应该在获得名字后立即测试空名字:

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

关于c - 当没有为名字输入值时如何使 for 循环中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43312224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com