#include <stdio.h>
#include <stdlib.h>
int main()
{
char *int_array ;
int no_els , i ;
printf("Enter the number of elements: ");
scanf("%d", &no_els );
int_array = (char *)malloc( no_els * sizeof( char )) ;
if( int_array == NULL )
printf("Cannot allocate memory\n");
else
{
for( i = 0 ; i < no_els ; i++ )
{
printf("Enter element %d: ", i+1 );
scanf("%c",int_array+i);
}
for( i = 0 ; i < no_els ; i++ )
printf("Enter %d is %c\n",i+1,*(int_array+i));
free ( int_array );
}
return 0 ;
}
scanf("%c",这句前加一个getchar()
你输入一个字符后按回车键了,这样会有一个换行符,需要用getchar()接收掉,否则scanf("%c"会接收这个换行符
在scanf();
之后加上getchar();
来忽略回车键
供参考:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* int_array;
int no_els, i;
printf("Enter the number of elements: ");
scanf("%d", &no_els);
getchar(); //修改
int_array = (char*)malloc(no_els * sizeof(char));
if (int_array == NULL)
printf("Cannot allocate memory\n");
else
{
for (i = 0; i < no_els; i++)
{
printf("Enter element %d: ", i + 1);
scanf(" %c", int_array + i); //修改
getchar(); //修改
}
for (i = 0; i < no_els; i++)
printf("Enter %d is %c\n", i + 1, *(int_array + i));
free(int_array);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *int_array ;
int no_els , i ;
printf("Enter the number of elements: ");
scanf("%d", &no_els );
getchar();
int_array = (char *)malloc( no_els * sizeof( char )) ;
if( int_array == NULL )
printf("Cannot allocate memory\n");
else
{
for( i = 0 ; i < no_els ; i++ )
{
printf("Enter element %d: ", i+1 );
scanf("%c",int_array+i);
getchar();
}
for( i = 0 ; i < no_els ; i++ )
printf("Enter %d is %c\n",i+1,*(int_array+i));
free ( int_array );
}
return 0 ;
}
scanf("%c",&c) 与 scanf(" %c",&c),后者只是在%前多了个空格,似乎没有什么区别,但使用起来区别是很大的。
scanf()作单字符输入时规定只接收一个字符,但它却把回车符也作为字符对待的。这个回车符是放在缓冲区的,但是空格却是直接忽略掉。
这就造成程序中第二次调用scanf("%c",&c)是从缓冲区中取一个字符,把第一次调用scanf("%c",&c)后输入的回车当作输入字符了。
这就在输入逻辑上造成了混乱。
有了scanf(" %c",&c)这个空格(换成\n或者\t也可以),这样就把缓冲区中的回车当成第一个字符,读取后丢掉。
————————————————
版权声明:本文为CSDN博主「zyh的打怪历程」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38786209/article/details/80425394