c - 我的二维数组在 do while 循环中不起作用

标签 c

当我创建一个像这样的数组时:array[tshelf][tslot] = item;有一个错误 运行代码时。知道为什么吗?我相信我做得正确,但是当我运行它时,它做了一些奇怪的事情。

typedef struct shelfitem {
    char str[75];
    int price;
} shelfitem;
int main() {
    int a;
    int s;

    printf("How many shelves are in the unit?\n ");
    scanf("%d", &a);
    printf("How many slots are available on each shelf to hold items?\n");
    scanf("%d", &s);

    shelfitem array[a][s];
    int tshelf;
    int tslot;
    char tempname[75];
    int tempprice;
    char q[75];
    int tcoord;
    int tcoord2;

    printf("You have created a shelving unit \n");

    do {
        printf("Please add a new item to the shelve by giving <name>,<price>,<shelf>,<slot> or type 'quit' when finished\n");
        scanf("%s, %d, %d, %d", tempname, &tempprice, &tshelf, &tslot);
        shelfitem item = {
                *tempname, tempprice
        };
      array[tshelf][tslot] = item; //THIS LINE IS THE ERROR
    } while (strcmp(tempname, "quit") != 0);

输出很奇怪。

最佳答案

scanf() 不是模式匹配函数。 %s 将处理直到下一个空白字符的所有内容;写入 %s, 不会使其在逗号之前停止。要使其名称中不包含逗号,您需要使用 %[^,] 而不是 %s。然后你需要在它前面放一个空格,这样它就会在处理输入之前跳过空格。

另一个问题是你不能使用简单的赋值来复制字符串; *tempname 仅引用数组的第一个字符。您需要使用strcpy()

在添加到数组之前,您应该检查“quit”输入,否则您将创建一个名为 quit 的项目。使用 while (1) 代替 do-while 循环,然后在用户输入“quit”时使用 break 停止循环。

#include <stdio.h>
#include <string.h>

typedef struct shelfitem {
    char str[75];
    int price;
} shelfitem;

int main() {
    int a;
    int s;

    printf("How many shelves are in the unit?\n ");
    scanf("%d", &a);
    printf("How many slots are available on each shelf to hold items?\n");
    scanf("%d", &s);

    shelfitem array[a][s];
    int tshelf;
    int tslot;
    char tempname[75];
    int tempprice;

    printf("You have created a shelving unit \n");

    while (1) {
        printf("Please add a new item to the shelve by giving <name>,<price>,<shelf>,<slot> or type 'quit' when finished\n");
        scanf(" %[^,], %d, %d, %d", tempname, &tempprice, &tshelf, &tslot);
        if (strcmp(tempname, "quit") != 0) {
            break;
        }
        strcpy(array[tshelf][tslot].str, tempname);
        array[tshelf][tslot].price = tempprice;
    }
}

请注意,由于您使用 scanf() 的方式,他们必须输入类似 quit,1,2,3 的内容。最好使用 fgets() 读取整行,测试 quit,然后调用 sscanf() 解析该行。

关于c - 我的二维数组在 do while 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898277/

相关文章:

c - 制定隐式规则和头文件

c - 为什么 &(&i) 在 C 中无效?

c - 如何在STM32F3上实现没有CubeMX的PWM?

c - 从 vivado 2015.2 迁移到 2016.4 后初始化和使用 SD 卡不起作用

c++ - 用 C 和 C++ 最快的输出到文件

c - 带 IPv6 的套接字

c - 关于操作系统的进程安排?

c++ - 错误修复。 OpenGL、GLSL Sprite 网格渲染问题

c++ - 从 Python 调用 C/C++?

c - 在 C 中解析代码会带来额外的字符