首页 > 解决方案 > C中的字符串和空格

问题描述

我得到格式 %s 需要 *char 类型的参数,但参数是 int 类型,这里出错,谁能帮我解决这个问题?这是一个简单的代码,但我还没有更精简的指针,我不知道如何解决这个问题。

int main()
{
  
  int items;
  int i;

     //main menu of the program
    printf("*********WELCOME TO ABC FASHION STORE***********\n");
    printf("\t\t\t1.Make a new sale\n\t\t\t2.Exit from POS system\n");
    printf("-----------------------------------------------------");

   printf("How many different types of items in your sales:");
   scanf("%d",&items);

   char code[items];
   int qty[items];
   for(i=0;i<items;i++)
   {
    printf("Enter the item code:");
    scanf("%s", code[i]);
    printf("Enter the quantity:");
    scanf("%d",&qty[i]);
   }

   //displaying the details of consumer
  printf("\nITEM CODE \t\t QUANTITY \t\t UNIT PRICE \t\t TOTAL\n");
  for(i=0;i<items;i++)
  {
   printf("%s\t\t%d\t\t", code[i],qty[i]);
  }

标签: arrayscstring

解决方案


对于初学者,您有:

   char code[items];
   ...
   scanf("%s", code[i]);

code字符数组也是如此,它code[i]代表单个字符——而不是字符串!你可能追求的是:

   #define MAX_LEN 50
   char code[items][MAX_LEN];
 ...
   scanf("%s", code[i]);

这使代码成为一个字符串数组,每个字符串MAX_LEN最长。

现在,上面有一个很大的安全问题——你没有指定数组的最大大小,用户可以输入一个很长的字符串,超出数组的末尾。聪明和恶意的用户可以使用它来覆盖程序中的其他内存部分......因此,为了解决这个问题,您可以限制 scanf 接受的字符串的大小: scanf("%50s", code[i]);,这将输入限制为 50 个字符。但是如果你改变MAX_LEN了,忘记改变宽度说明符,你就会遇到麻烦。此处描述了正确的解决方案;

   #define MAX_LEN 50
   #define STR(x) _STR(x)
   #define _STR(x) #x
   char code[items][MAX_LEN];
 ...
   scanf("%" STR(MAX_LEN) "s", code[i]);

对于 printf,您的问题是同一个问题 -code[i]是一个字符,而不是字符串指针,因此它与%s格式说明符不一致。如果您切换code为字符串数组,它将起作用。


推荐阅读