包含字符串的数组

时间:2015-02-10 21:11:07

标签: c arrays string

嘿我正在尝试创建一个发票程序,该程序应该接受项目名称,项目价格和数量,并将它们存储在列表或数组中。当我运行程序但是我得到错误。有人可以帮忙吗?我是菜鸟,不知道我怎么出错了,这个概念很简单..

以下是该计划:

#include <string.h>
#include <conio.h>

int main()
  {
   char item_name[255];
   float item_price=0;
   float quantity;
   int choice;
   int k;

   for (k=0;choice != 2;k++)
    {
       printf ("Enter item name: ");
       scanf ("%s", item_name[k]);
       printf ("\n");
       printf ("Enter item price: ");
       scanf ("%f", &item_price[k]);
       printf ("\n");
       printf ("Enter item quantity: ");
       scanf ("%f", &quantity[k]);
       printf ("\n\n");
       printf ("Enter another item? Enter '1' for yes and '2' for no: ");
       scanf ("%d", &choice);
    }

  }

这些是错误:

sample.c:在函数'main'中: sample.c:15:8:警告:格式'%s'需要类型'char *'的参数,但参数2的类型为'int'[-Wformat =]         scanf(“%s”,item_name [k]);         ^ sample.c:18:32:错误:下标值既不是数组也不是指针也不是向量         scanf(“%f”,&amp; item_price [k]);                                 ^ sample.c:21:30:错误:下标值既不是数组也不是指针也不是向量         scanf(“%f”,&amp; quantity [k]);                               ^ sample.c:25:5:错误:预期';'在'}'标记之前      }      ^ sample.c:8:10:警告:变量'quantity'设置但未使用[-Wunused-but-set-variable]     浮动量;           ^ sample.c:7:10:警告:变量'item_price'设置但未使用[-Wunused-but-set-variable]     float item_price = 0;           ^

1 个答案:

答案 0 :(得分:1)

char item_name[255];

是单个字符串 - 不是字符串数组。

item_name[k]

是一个字符 - 而不是字符*

所以你需要让item_name成为一个2D字符串数组

char item_name[100][255];

然后使用

scanf ("%s", item_name[k]);

下一个问题是item_price。它也需要是一个数组:

float item_price[100];

与浮动数量相同的故事

float quantity[100];

然后你错过了一个&#34 ;;&#34;在最后一次扫描结束时

最后你需要添加

if (choice == 2) break;

离开循环。

建议的代码允许100个项目,所以你应该添加:

if (k > 99) break;

作为for循环中的第一行