我只是尝试了一个简单的C程序,插入到数组中。 我用scanf
函数来接受字符,但它似乎只是编译器跳过了,只是程序结束。 这是我使用的代码: -scanf函数不能使用字符
#include <stdio.h>
void main()
{
int a[50], i, j, m, n, x;
char ch;
printf("Enter the no. elements of the array :- ");
scanf("%d", &m);
printf("Enter the elements below :- ");
for (i = 0; i < m; i++)
{
scanf("%d", &a[i]);
}
printf("The array is :- \n");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
printf("\nDo you want to enter an element ? (Y/N)\n");
scanf("%c", &ch); // The compiler just skips this along with the
while (ch == 'y' || ch == 'Y') // while loop and goes straight to the printf
{ // statement
printf("The index of the element :- ");
scanf("%d", &n);
printf("\nEnter a number :- ");
scanf("%d", &x);
for (i = m; i > n; i--)
{
a[i] = a[i - 1];
}
a[n] = x;
printf("\nInsert more numbers ? (Y/N)");
scanf("%c", &ch);
m = m + 1;
}
printf("\nThe array is :- ");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
}
我使用的可变ch
以允许用户有选择的,不论是否插入元素即Y
或N
。
但编译器基本上跳过第三个scanf
函数,它接受char
以及while
循环。
我只想知道为什么scanf
函数被跳过?
请将'scanf(“%c”,&ch);''改为'scanf(“%c”,&ch);'以便消耗缓冲区中剩下的换行符。与其他格式不同,'%c'不会自动跳过输入缓冲区中的空白。 –
可能重复[Scanf Skip scanning character](http://stackoverflow.com/questions/36281871/scanf-skip-scanning-character) – EOF
....并且请张贴好缩进代码... – LPs