简体   繁体   English

将字符数组传递给函数内的结构数组

[英]Passing char array to a struct array within a function

As mentioned in the title, I don't know how to pass a char array to a struct array within a function.正如标题中提到的,我不知道如何将 char 数组传递给函数内的 struct 数组。

The task is to write a little warehouse system, where you can add / remove / search for items.任务是编写一个小仓库系统,您可以在其中添加/删除/搜索项目。 But in order to add / remove a Item, it should be checked whether the item already exists or not.但是为了添加/删除一个项目,应该检查该项目是否已经存在。

I have to use a struct and an array of this struct.我必须使用一个结构体和一个这个结构体的数组。 My current approach is really buggy and I tried several hours to fix this but at this point I don't even know what to fix..我目前的方法确实有问题,我尝试了几个小时来解决这个问题,但此时我什至不知道要解决什么..

Important note: I am not allowed to use any other library than stdio.h and string.h and I am not allowed to use anything else than scanf for input and printf for output .重要提示:我不允许使用任何其他库比stdio.h中和string.h中,我不允许使用任何东西比scanf函数输入和printf输出 I have to compare both strings with strcmp and I don't think that I am allowed to use strncpy .我必须将两个字符串与strcmp进行比较,我认为我不允许使用strncpy

Perhaps my whole approach is wrong..也许我的整个方法是错误的..

Here is my code这是我的代码

#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

To put a string into another array without strncpy() , you can use strcpy() .要在没有strncpy()情况下将字符串放入另一个数组中,您可以使用strcpy()

strcpy(wHouse[i].item, inputItem);

Another way is to calculate length to copy via strlen() and copying via memcpy() .另一种方法是通过strlen()计算要复制的长度并通过memcpy()复制。

size_t len = strlen(inputItem);
memcpy(wHouse[i].item, inputItem, len + 1); /* +1 for terminating null character */

If both of these ways are not allowed, you can copy each characters by yourself.如果这两种方式都不允许,您可以自己复制每个字符。

for (size_t p = 0; ; p++) {
    wHouse[i].item[p] = inputItem[p];
    /* break here (not via loop condition) instead of loop condition for copying terminating null character */
    if (inputItem[p] == '\0') break;
}

And I found three other problems in your code.我在你的代码中发现了另外三个问题。

Firstly, the array wHouse is used without initializing, so you are using indeterminate values for calculation and invoking undefined behavior .首先,数组wHouse在没有初始化的情况下使用,因此您使用不确定的值进行计算和调用未定义的行为

Initlalization can be done like this:初始化可以这样完成:

WareHouse wHouse[NUMBEROFITEMS] = {{"", 0}};

You can specify the value for only first element, and the left elements will be automatically initialized to "zero".您可以只为第一个元素指定值,左边的元素将自动初始化为“零”。

Secondly, the choice is displayed twice because newline characters are read via %c .其次,选择显示两次,因为换行符是通过%c读取的。 To avoid this, you can add a space characte before %c to tell scanf ignore whitespace characters.为了避免这种情况,您可以在%c之前添加一个空格字符来告诉scanf忽略空白字符。

scanf(" %c", &decision);

Thiredly, if you add the "passing" in the newItem() function like you say, all elements will be modified because elements are modified for all values that strcmp() returns.第三,如果你像你说的那样在newItem()函数中添加“传递”,所有元素都将被修改,因为元素被修改为strcmp()返回的所有值。 Instead, I guess you want to modify the first empty element when specified item is not found.相反,我猜您想在未找到指定项目时修改第一个空元素。

To realize this, you can write like this:为了实现这一点,你可以这样写:

void newItem(char *inputItem, WareHouse *wHouse , int inputNumber) {

    int itemFound = 0; /* set to 1 when specified item is found */
    int firstEmptyItem = -1; /* set to the index of the first empty item */

    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;

            itemFound = 1; /* the item is found! */

        } else if (strcmp("", wHouse[i].item) == 0) { /* check if this item is empty */
            /* if empty and index is not written yet, write the index */
            if (firstEmptyItem < 0) firstEmptyItem = i;

        }
    }
    /* if the item is not found, and a room to add new item exists */
    if (!itemFound && firstEmptyItem >= 0) {
        int i = firstEmptyItem; /* set index (or you can use firstEmptyItem directly in the following code) */

        wHouse[i].number+= inputNumber;

        /* Here you should pass the "inputItem" into the "wHouse" array. */
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM