C将字符数组初始化为字符串,但在尝试printf时为空
我想打印字符数组(作为字符串),但它在运行时显示一个空字符串 初始化:C将字符数组初始化为字符串,但在尝试printf时为空,c,C,我想打印字符数组(作为字符串),但它在运行时显示一个空字符串 初始化: char str1[6]= "Black"; char str2[7]= "Yellow"; printf声明: printf ("%s = %d Bath\n",str1,a); printf ("%s = %d Bath\n",str2,a); 预期: Black = 150 Bath Yellow = 1
char str1[6]= "Black";
char str2[7]= "Yellow";
printf声明:
printf ("%s = %d Bath\n",str1,a);
printf ("%s = %d Bath\n",str2,a);
预期:
Black = 150 Bath
Yellow = 150 Bath
输出
Black = 150 Bath
= 150 Bath
我尝试在没有大小编号的情况下初始化,如char str2[]=“黄色”代码>
或使用C++ CUT显示
原始代码:
#包括“stdio.h”
#包括“conio.h”
main(){
字符str1[6]=“黑色”;
字符str2[7]=“黄色”;
字符大小,E='E',S='S',M='M',L='L';
收到款项、零钱、所需金额;
INTA=150;
int b=180;
int c=200;
int d=220;
而(1){
printf(“选择您的尺寸”(S、M、L)或E退出=,尺寸);
scanf(“%s”、&size);
如果(大小==E){
返回0;
}else if(大小==S){
printf(“%s=%d-Bath\n”,str1,a);
printf(“%s=%d-Bath\n”,str2,a);
printf(“所需金额?=”);
scanf(“%d”和所需金额);
printf(“收钱?=”);
scanf(“%d”和“接收资金”);
printf(“变更?=”);
变更=((收款*所需金额)-150);
printf(“%d浴\n”,更改);
printf(“\n------------------\n”);
}否则,如果(尺寸==M){
printf(“%s=%d\n”,str1,b);
}else if(尺寸==L){
printf(“%s=%d-Bath\n”,str1,c);
}
}
}
您告诉系统将字符串(由于%s
)扫描为单个字符(即大小
)
就是
对字符使用%c
顺便说一句:
使用scanf
时,应始终检查返回值是否等于预期扫描的元素数
因此,不是:
scanf("%d",&requiredamount);
你应该做:
if (scanf("%d",&requiredamount) != 1)
{
// Could not scan integer - add error handling
}
您的问题在这里:scanf(“%s”和&size)代码>
更改为:scanf(“%c”和&size)代码>
它对我起作用,但不是C++,反之亦然。你收到编译警告了吗?首先修复这些问题,然后再返回。注意:main()
在C afaik中不是有效的签名。将其设置为int main()
printf(“选择您的尺码?(S、M、L)或E以退出=”,size)代码>编译器应该显示一些关于与格式说明符不匹配的额外参数size
的警告。
if (scanf("%d",&requiredamount) != 1)
{
// Could not scan integer - add error handling
}