arrays - 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]);
}
解决方案
对于初学者,您有:
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
为字符串数组,它将起作用。
推荐阅读
- python - 将 HTML 表从受密码保护的页面保存到外部 HTML 文件
- c# - 如何将 XML 数据作为参数传递给从 C# 到 Sql 服务器的 TVP 参数
- asp.net-core - Microsoft.Extensions.Cashing.Redis 和 Microsoft.Extensions.Caching.StackExchangeRedis.RedisCache 之间的区别
- javascript - 如何在 Javascript 中创建独特的数组元素组合?
- python - 创建列以跟踪另一列中的缺失值
- r - 将 R 表达式沿轴分成两行
- extjs - 无法从“XMLHttpRequest”读取“responseText”属性
- visual-studio-2019 - 是否有 Visual Studio 2019 组合解决方案的方法?
- javascript - 为什么这个 JavaScript 小书签会清除页面?
- firebird - 在firebird中的表格中插入多行