2017-02-24 201 views
0
#include <math.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <assert.h> 
#include <limits.h> 
#include <stdbool.h> 

int main() 
{ 
    int n,i; 
    char a[10][100]; 
    printf("\n Enter the no. of strings:"); 
    scanf("%d",&n); 

    printf("\n enter the %d numbers:",n); 

    for(i=0;i<n;i++) 
    { 
     printf("\n %d",i); 

     gets(a[i]); 
    } 
    for(i=0;i<=n;i++) 
     { 
      puts(a[i]); 
     } 
    return 0; 
} 

如果n = 3那么在指数1只需要两个字符串和2它跳过0,为什么没有采取输入在0获取C输入()函数在数组

这里a是我的字符串数组。

+1

'gets'是一个不可能正确使用的函数。因此,它已从最新的C标准中删除。使用它是一个错误。请考虑使用'fgets'来代替。 – user694733

+2

因为它之前的'scanf'离开了输入缓冲区中的'\ n',并且'gets'在第一次迭代中读取它。顺便说一句,[**不要使用'gets' **。这是危险的!](http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) –

回答

0

的原因错误的行为是scanf不读取ENTER这是必要的,以确认n输入。如果添加的getsdummy调用它:

#include <math.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <assert.h> 
#include <limits.h> 
#include <stdbool.h> 

int main() 
{ 
    int n,i; 
    char a[10][100]; 
    printf("\n Enter the no. of strings:"); 
    scanf("%d",&n); gets(a[0]); 

    printf("\n enter the %d numbers:",n); 

    for(i=0;i<n;++i) 
    { 
     printf("\n %d",i); 

     gets(a[i]); 
    } 
    for(i=0;i<n;++i) 
     { 
      puts(a[i]); 
     } 
    return 0; 
} 

diff我的版本与原来的一个。我确实解决了输出循环中的另一个问题。

+0

谢谢!它的工作原理我 – ash