在C中向数组添加数据

时间:2012-09-28 13:49:46

标签: c linux arrays string

我想要更新一些数组。问题是当数据添加到数组时,一些变量会更新为0。

我的代码添加数据:

void addStockItem(){
    system(CLS_NAME);
    printf("New Item\n\n");
    printf("New Item Name   : ");
    fflush(stdin);
    scanf(" %[^\n]s",&*itemName[totalItem]);
    //itemName[totalItem][30] = strupr(itemName[totalItem]);
    fflush(stdin);
    printf("New Item Price  : ");
    scanf("%f",&item_Price_Profit[totalItem][0]);
    printf("New Item Profit : ");   
    scanf("%f",&item_Price_Profit[i][1]);
    printf("New Item Qty    : ");   
    scanf("%d",&itemQuantity[totalItem][0]);
    itemQuantity[totalItem][1]=0;
    itemQuantity[totalItem][2]=0;
    ++totalItem;
    allStocks();
}

数据,

int totalItem=13,itemQuantity[][3]={8,0,0,9,0,0,11,0,0,0,0,0,20,0,0,22,0,\
  0,16,0,0,18,0,0,9,0,0,7,0,0,5,0,0,12,0,0,0,0,0},sessionQuantity;

float item_Price_Profit[][2]={1,0.5,2,0.2,3,0.2,4,0.2,5,0.5,6,0.8,7,0.5,8,0.2,9,\
0.2,10,0.2,11,0.5,12,0.8,13,0.9};

char itemName[][30]={"STABILO PENCIL 2B","STABILO PEN 0.5",\
"STABILO ERASER","STABILO RULER","STABILO TEST PAD","STABILO BOOK","STABILO SCISSORS","STABILO SHARPENER","STABILO GLUE","STABILO CHALK","STABILO MARKER PEN","OXFORD DICTIONARY","STABILO HIGHLIGHTER"};

完整代码:http://pastebin.com/jjuCCrjz

[编辑] 在将itemQuantity [] [3]更改为itemQuantity [100] [3],item_Price_Profit [] [2]至item_Price_Profit [100] [2]和itemName [] [30]至itemName [100]之后,所有内容都按预期工作[30]。什么可能是我的错误除了scanf?

2 个答案:

答案 0 :(得分:3)

我无法从我的工作计算机访问pastebin,所以我必须按照发布的内容进行操作。

有几个问题:

  1. fflush仅定义为处理输出流,而不是输入流; fflush(stdin)的行为未定义(它会执行某些,但可能不是您想要的)。如果您需要清除输入流中的垃圾,则需要使用getchar()fgets()或类似信息来消耗它,直到您看到换行符或其他指示符已清除垃圾为止。 %f%d转换说明符将跳过任何前导空格,并且在%[转换说明符之前使空格也会导致跳过任何前导空格。所以完全抛弃了fflush个电话。

  2. scanf(" %[^\n]s",&*itemName[totalItem]); - 这看起来很混乱。除非您希望输入始终具有尾随s字符,否则转换说明符应该只是%[^\n]&*前面的itemName是多余的;你只需要写

    scanf(" %[^\n]", itemName[totalItem]);
    虽然你应该在那里放一个字段宽度说明符:
    scanf(" %30[^\n]", itemName[titalItem]);
    避免缓冲区溢出。

  3. 您正在访问所有数据项(totalItemitemNameitem_Price_Profit等)作为全局变量。这通常是胃灼热的一个方法。理想情况下,函数及其调用者不应通过全局变量共享状态;相反,它们应该通过参数,返回值和异常(在支持的情况下)进行通信。更像

     void addStockItem(char *name, float *price, float *profit, float *quantity)
     {
       ...
       scanf(" %30[^\n]", name);
       ...
       scanf("%f", price);
       ...
       scanf("%f", profit);
       ...
       scanf("%d", quantity); 
     }
    的内容,可以称为
     addStockItem(itemName[totalItem], 
                  &item_Price_Profit[totalItem][0], 
                  &item_Price_Profit[i][1], 
                  &itemQuantity[totalItem][0]);

  4. 您的数据结构对我来说真的很不好,但这可能是因为我无法看到您的整个程序。

答案 1 :(得分:2)

此:

scanf(" %[^\n]s",&*itemName[totalItem]);

不可能是对的。这是传递转换为指针的字符,其中scanf()需要指向字符的指针。你可能意味着:

scanf(" %[^\n]s", itemName[totalItem]);