【发布时间】:2020-04-01 04:16:36
【问题描述】:
正如标题中提到的,我不知道如何将 char 数组传递给函数内的 struct 数组。
任务是编写一个小仓库系统,您可以在其中添加/删除/搜索项目。但是为了添加/删除一个项目,应该检查项目是否已经存在。
我必须使用一个结构和这个结构的数组。我目前的方法确实有问题,我尝试了几个小时来解决这个问题,但此时我什至不知道要修复什么..
重要提示:我不允许使用 stdio.h 和 string.h 以外的任何其他库,并且我不允许使用除了 scanf 输入和 printf 输出以外的任何东西。我必须将这两个字符串与 strcmp 和 我不认为 我被允许使用 strncpy 进行比较。
也许我的整个方法都是错误的..
这是我的代码
#include <stdio.h>
#include <string.h>
#define LENGTHITEM 100
#define NUMBEROFITEMS 100
typedef struct WareHouse_ {
char item[LENGTHITEM];
int number;
} WareHouse;
void newItem(char*, WareHouse*, int);
int main() {
int end = 0; int inputNumber = 0;
char decision; char inputItem[NUMBEROFITEMS];
WareHouse wHouse[NUMBEROFITEMS];
printf("\nWelcome!");
printf("\n\nYou can choose the following:");
while (end != 1) {
printf("\n\nNew Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): ");
scanf("%c", &decision);
switch(decision) {
case 'h':
case 'H': printf("\nName: ");
scanf("%s, inputItem);
printf("Number: ");
scanf("%i", &inputNumber); <-- Here it says: scanf used to convert a string to an integer value (CLion)
newItem(inputItem, wHouse, inputNumber);
break;
case 'e':
case 'E': printf("\nTest E");
break;
case 's':
case 'S': printf("\nTest S");
break;
case 'a':
case 'A': printf("\nTest A");
break;
case 'b':
case 'B': printf("\nGood bye!");
end++;
break;
}
}
return 0;
}
void newItem(char *inputItem, WareHouse *wHouse , int inputNumber) {
for (int i = 0; i < NUMBEROFITEMS; i++) {
if (strcmp(inputItem, wHouse[i].item) == 0) {
printf("\nItem already exists, number increased %i", inputNumber);
wHouse[i].number+= inputNumber;
} else if (strcmp(inputItem, wHouse[i].item) < 0 || strcmp(inputItem, wHouse[i].item) > 0) {
wHouse[i].number+= inputNumber;
<-- Here I want to pass the "inputItem" into the "wHouse" array but I don't know how.. -->
}
}
}
Program:
Welcome
You can choose the following:
New Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): H <-- My input
Name and number (Name Number): fish 10 <-- My input
New Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): <-- BUG IT APPEARS TWO TIMES
New Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): H
Name and number (Name Number): fish 10 <-- My input
<-- Here it should output: "Item already exists, number increased 10" but it does nothing -->
New Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): <-- BUG IT APPEARS TWO TIMES
New Item (H) / Delete Item (E) | Search Item (S) | Table (A) | End (B): B
Good bye
【问题讨论】:
-
你的 else 子句没有意义,是吗?如果 strcmp 不匹配,如何确保不会覆盖现有项目?另外,为什么不单独阅读字符串和金额?更经常推荐使用 fgets 来读取字符串。另外,fflush 有什么作用?
-
仅供参考,无论书籍、网站、教程或熟人告诉你
fflush(stdin);是清除stdin流的标准方法,他们都错了。 See here. -
@user0800 如前所述,我不允许使用 fgets.. 我的 else 应该说“如果项目不存在”。
-
@WhozCraig 我的教授做了。
-
对,我错过了那个。你如何防止覆盖?