如何避免C中的sscanf()导致无限while循环而不是存储用户输入?
我已经在一个C项目上工作了一段时间了,我对C相当陌生,到目前为止我已经尝试了多种方法,但似乎都不管用。每当我进入while循环并进入sscanf()函数时,循环就变得无限大,无法接受输入。这意味着我无法获取并存储在mt 2d数组中 我还尝试使用strtok()作为另一个选项,但代码变得太混乱如何避免C中的sscanf()导致无限while循环而不是存储用户输入?,c,string,multidimensional-array,while-loop,scanf,C,String,Multidimensional Array,While Loop,Scanf,我已经在一个C项目上工作了一段时间了,我对C相当陌生,到目前为止我已经尝试了多种方法,但似乎都不管用。每当我进入while循环并进入sscanf()函数时,循环就变得无限大,无法接受输入。这意味着我无法获取并存储在mt 2d数组中 我还尝试使用strtok()作为另一个选项,但代码变得太混乱 typedef struct item { char name[50]; double price; } item; int main() { // 1 begins c
typedef struct item {
char name[50];
double price;
} item;
int main() {
// 1 begins
char userInput[100];
printf("Hello, welcome to the shelf-O-matic!\n");
printf("Please press enter and then type the number of shelves followed by ',' and number of slots\n");
int shelf = 0;
int slot = 0;
scanf("%d , %d", &shelf, &slot);
struct item **thing = malloc(shelf * sizeof(item));
for (int i = 0; i < slot; i++) {
thing[i] = malloc(slot * sizeof(item));
}
while (strcmp(userInput , "quit")!= 0) {
//variables symbolizing the slots and shelves
printf("type quit to exit or set input to the array\n");
//scanf("%100s", userInput);
//Putting the size in memory location
double *cash = malloc(sizeof(cash));
int *x = malloc(sizeof(x));
int *y = malloc(sizeof(y));
//scanf("%100s", userInput);
// 1 ends
char *itemName = malloc(sizeof(itemName));
printf("Please add things to the shelves and slots by specifying <name> <price> <shelf> <slot> or type quit to finish adding\n");
sscanf(userInput,"%100s, %lf, %d, %d", itemName, &cash, &x, &y);
printf(itemName);
printf(cash);
printf(x);
printf(y);
}
return 0;
}
typedef结构项{
字符名[50];
双倍价格;
}项目;
int main(){
//1开始
字符用户输入[100];
printf(“你好,欢迎来到shelf-O-matic!\n”);
printf(“请按enter键,然后键入托架数,后跟“,”和插槽数\n”);
int-shelf=0;
int槽=0;
scanf(“%d,%d”,&shelf,&slot);
结构项目**物品=malloc(货架*尺寸(项目));
对于(int i=0;i
预期的结果应该是内存中的输入,以便以后可以将其分配给数组值并打印出来进行验证。我不确定您在这里试图实现什么,但您的userInput应该首先正确初始化,您可以使用类似这样的内容:char userInput[100]={'\0'];另外,您正在使用sscanf inside while循环为userInput分配一个新值,该值正在根据itemName进行初始化,itemName只得到malloc,但从未被分配任何值。如果您想从用户处获取userInput的值,那么您应该使用userInput进行扫描。我刚刚尝试过,遗憾的是它没有改变设置在这种情况下,我粘贴的代码基本上是一个测试,以查看值是否被分配给它们的变量,但循环在到达sscanf()行时似乎变得无限。无限循环问题是由以下语句引起的:while(strcmp(userInput,“quit”)。如果这不是完整的代码,则应使用调试器调试代码。