2017-02-21 97 views
0

我只是尝试了一个简单的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以允许用户有选择的,不论是否插入元素即YN

但编译器基本上跳过第三个scanf函数,它接受char以及while循环。

我只想知道为什么scanf函数被跳过?

+2

请将'scanf(“%c”,&ch);''改为'scanf(“%c”,&ch);'以便消耗缓冲区中剩下的换行符。与其他格式不同,'%c'不会自动跳过输入缓冲区中的空白。 –

+3

可能重复[Scanf Skip scanning character](http://stackoverflow.com/questions/36281871/scanf-skip-scanning-character) – EOF

+0

....并且请张贴好缩进代码... – LPs

回答

5

回到上一个scanf这是最后一个数组成员。

scanf("%d",&a[i]) 

输入文件,如果你输入:

32\n 
^^ 

输入将读十进制数后仅换行前等待。

在这会导致问题scanf

scanf("%c", &ch); 

它会读取换行符,因为它是提供输入这就是为什么它会被隐式执行后,跳过该行。

要忽略空白,只需在说明符%c之前添加空格,如@xing和@WeatherVane的注释中所述。

scanf(" %c",&ch); 

C99 7.19.6.2

输入空白字符(由isspace为函数指定) 被跳过除非说明书包括[,c或n 说明符250)

+1

好答案+1。但考虑使用吨作为重复的以前的答案 – LPs

+0

这个问题也是重复的,但似乎没有从OP –

+0

'scanf'没有很好的理解“它会读取换行符,因为它是可用的输入,这就是为什么它会跳过它 忽略空白“我没有完全明白。请详细说明为什么scanf函数skipps,因为它前面有一个\ n存在。 – steve