我的论文中有一个问题。我有10个员工ID M001,A004,D007等...用户正在输入上述ID中的一个,如果id不存在则打印未找到的ID。我厌倦了strcmp并被卡住了。如果你告诉我一个方法,这很好吗?谢谢,请注意:我是C.的初学者。我正在尝试一种简单的方法,现在它给出了for循环的错误。
下标值既不是数组也不是指针,也不是向量
#include<stdio.h>
#include<string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status,input,search,C,P;
char searchId[8][4]={"M001","A004","D007","D010","D012","Q008","Q015","DE09"};
float salary,bonus,tSalary;
int i,j;
do{
printf("Enter the employee id: ");
scanf("%s", &search);
printf("Enter the job status: ");
scanf("%s", &status);
printf("Enter the salary: ");
scanf("%f", &salary);
for(i=0;i<8;i++){ //This is where all things go wrong
for(j=0;j<4;j++){
if(searchid[i][j]=search){ //the [i] where the subscripted error occurs
printf("Id is valid\n");
}
else printf("Invalid id\n");
}
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
}while(input=='Y'||input=='y');
return 0;
}
答案 0 :(得分:2)
发布的代码中存在很多问题。对于初学者,searchId
应声明为searchId[8][5]
,以便在每个字符串末尾为\0
终结符腾出空间。
从输入代码中可以看出status
和search
应该包含字符串,但这些字符串被声明为char
s。修复此问题后,请注意在调用这些数组的&
调用中不需要地址运算符scanf()
。此外,在%s
转换说明符与scanf()
一起使用时,应始终指定最大宽度,以避免缓冲区溢出。
使用==
比较运算符无法比较字符串,因此应在此处使用strcmp()
。这可以在循环遍历字符串数组的循环中完成;索引达到8时循环退出,或者比较成功。然后,在循环之后,如果索引已达到8(所有有效的id字符串都未通过测试),则search
字符串无效。
以下是已发布代码的修改版本,它实现了所有这些:
#include <stdio.h>
#include <string.h>
float tSalary(float salary,float bonus);
char searchid(char search);
int main(void)
{
char status[1000];
char search[1000];
char input, C, P;
char searchId[8][5] = { "M001", "A004", "D007", "D010",
"D012", "Q008", "Q015", "DE09" };
float salary, bonus, tSalary;
int i, j;
do {
printf("Enter the employee id: ");
scanf("%999s", search);
printf("Enter the job status: ");
scanf("%999s", status);
printf("Enter the salary: ");
scanf("%f", &salary);
i = 0;
while (i < 8 && strcmp(search, searchId[i]) != 0) {
++i;
}
if (i < 8) {
printf("Id is valid\n");
} else {
printf("Invalid id\n");
}
printf("Do you want to enter another record?(Y-Yes/N-No): ");
scanf(" %c", &input);
} while (input == 'Y' || input == 'y');
return 0;
}
示例程序交互:
Enter the employee id: A004
Enter the job status: pending
Enter the salary: 2000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: Q015
Enter the job status: completed
Enter the salary: 3000
Id is valid
Do you want to enter another record?(Y-Yes/N-No): y
Enter the employee id: B001
Enter the job status: completed
Enter the salary: 1200
Invalid id
Do you want to enter another record?(Y-Yes/N-No): n