C 使用isdigit后如何将字符串打印到数组中?
我对isdigit和弦很陌生。我真的需要你们的帮助。我想将字符串打印到数组“food[f]”中。但你们能帮我检查一下我的问题出在哪里吗?这是我的密码C 使用isdigit后如何将字符串打印到数组中?,c,C,我对isdigit和弦很陌生。我真的需要你们的帮助。我想将字符串打印到数组“food[f]”中。但你们能帮我检查一下我的问题出在哪里吗?这是我的密码 #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main() { char foo[20]; float price; int number=1; int f=0,i=0; char *food
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char foo[20];
float price;
int number=1;
int f=0,i=0;
char *food[f];
adding_food :
food[f] = (char*)malloc(25);
printf("Adding food into Menu (0 to Main Menu): ");
scanf("%s", foo);
{
if(isdigit(foo[0])== 0)
{
foo[i] = *food[f]; //something wrong here
printf("Enter price (RM) : ");
scanf("%f",&price);
printf("\n%-16d%-19s%6.2f\n\n",number,foo,price);
printf("\n%-16d%-19s%6.2f\n\n",number,food[f],price);
number++;
i++;
f++;
goto adding_food;
}
else
return 0;
}
}
#包括
#包括
#包括
int main()
{
查富[20];
浮动价格;
整数=1;
int f=0,i=0;
炭*食品[f];
添加食物:
食物[f]=(半焦*)马洛克(25);
printf(“将食物添加到菜单(0添加到主菜单):”;
scanf(“%s”,foo);
{
if(isdigit(foo[0])==0)
{
foo[i]=*食物[f];//这里有什么问题吗
printf(“输入价格(RM):”;
scanf(“%f”和“价格”);
printf(“\n%-16d%-19s%6.2f\n\n”,数字,foo,价格);
printf(“\n%-16d%-19s%6.2f\n\n”,数字,食品[f],价格);
数字++;
i++;
f++;
后藤添加食物;
}
其他的
返回0;
}
}
我希望我的输出是这样的
将食物添加到菜单中(0到主菜单):蛋糕
输入价格(RM):10
1蛋糕10//foo[0]
1蛋糕10//食物[0]
您的代码中有几个错误。例如:
char *food[f];
类似于
char *food[0];
asf
为零。这毫无意义
此外,使用goto
也被认为是不好的风格
所以,让我向你们展示另一种方法。比如:
// Make a type that can hold both a name and a price
struct item
{
char name[25];
float price;
};
#define MAX_ITEMS 100
struct item* addItems(int* n)
{
*n = 0;
struct item* items = malloc(MAX_ITEMS * sizeof *items);
if (items == NULL) return NULL;
while (*n != MAX_ITEMS)
{
scanf("%24s", items[*n].name);
if (items[*n].name[0] == '0') break;
scanf("%f", &items[*n].price);
*n += 1;
}
return items;
}
void print_all(struct item* my_items, int num_items)
{
for (int i = 0; i < num_items; ++i)
printf("%s %f\n", my_items[i].name, my_items[i].price);
}
int main()
{
int num_items;
struct item* my_items = addItems(&num_items);
print_all(my_items, num_items);
free(my_items);
}
//创建一个既能保存名称又能保存价格的类型
结构项
{
字符名[25];
浮动价格;
};
#定义最多100个项目
结构项*附加项(int*n)
{
*n=0;
struct item*items=malloc(MAX_items*sizeof*items);
如果(items==NULL)返回NULL;
而(*n!=最大项目数)
{
scanf(“%24s”,项[*n].name);
如果(项[*n].name[0]='0')中断;
scanf(“%f”,&items[*n]。价格);
*n+=1;
}
退货项目;
}
全部作废打印(结构项*我的项,整数项)
{
对于(int i=0;ichar*食物[f]代码>计算为char*food[0]代码>-零大小数组!还有,为什么在这个代码中使用goto
?因为我可能会在菜单中添加更多的食物,所以我仍然必须将其保持为f,以便在菜单中添加多个食物。此外,我使用了goto
进行循环。它不是这样工作的,数组的大小不会因为修改变量而神奇地增长。而goto
是一个可怕的循环工具。使用实际循环代替。您的编译器也应该抱怨大部分代码,千万不要忽略编译器警告@我真的不知道下一步该怎么做才能让程序正常运行。你能为我做一个可以输入多个输入(字符串)的示例解决方案吗?非常感谢。@JeremyWan你希望isdigit做什么?非常感谢!但是,如果我想打印一些选定的食物,我应该在哪里更改?例如,我有1。蛋糕,2。面包,3。金枪鱼4。奶酪。那么我只想购买(或印刷)面包和奶酪。我该怎么办。(我不能简单地将项目代码3设置为金枪鱼,因为金枪鱼是附加的。)所以我可能想在这里更改。而不是for
循环void print_all(struct item*my_items,int num_items){for(int i=0;i
,这就是我尝试使用该数组的原因。