我的程序包含 character 的输入代码,但在调试期间没有考虑它。
它考虑其他数据类型(int、float 等)的输入
程序:
#include<stdio.h>
int main()
{
int n,i=0;
char c;
scanf("%d",&n);
int a[20];
while(1)
{
scanf("%c",&c);
if(c=='\n')
break;
else
{
if(c!=32)
a[i++]=c-48;
}
}
for(i=0;i<10;i++)
printf("%d ",a[i]);
return 0;
}
最佳答案
您的 scanf("%d",...)
在缓冲区中留下一个换行符,然后立即由后续的 scanf("%c",. ..)
。为了克服这个问题,只让 scanf("%d",...)
之后的一个 scanf
消耗空格:
int main()
{
int n,i=0;
scanf("%d",&n);
int a[20];
char c=0;
scanf(" %c",&c); // Consume white spaces including new line character before the value for c.
while(c!='\n' && i < 20)
{
if(c!=32) {
a[i++]=c-'0';
}
scanf("%c",&c);
}
for(int x=0;x<i;x++)
printf("%d ",a[x]);
return 0;
}
关于使用 gdb 调试时的字符/字符串输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358111/