【发布时间】:2017-02-21 15:40:05
【问题描述】:
我只是在用 C 语言尝试一个简单的程序,插入一个数组。
我使用了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不会自动跳过输入缓冲区中的空白。 -
....请发布缩进良好的代码...
-
编译器不关心你按下的键。它仅从您的源代码生成可执行程序。这个可执行程序(以及您编译生成它的源代码)负责正确处理输入。读取数字的代码不会消耗按
<Enter>时产生的换行符,然后下一个scanf("%c")会读取换行符,这就是代码无法按预期工作的原因。