2014-03-13 90 views
0

我是C编程新手,我不知道我能在这段代码中改变什么,如果我编译这段代码,它只显示n次的姓氏。为什么它不会显示其他名称,请帮助专家。谢谢!如何使用for循环打印输入的字符串?

#include<stdio.h> 
#include<string.h> 
#include<malloc.h> 
int main() 
{ 
    int a; 
    char n[50]; 
    printf("enter the number of students:\n"); 
    scanf("%d",&a); 
    printf("enter the names of the students\n"); 
    int i; 
    for(i=0;i<a;i++) 
    { 
     scanf("%s",n); 
    } 

    for(i=0;i<a;i++) 
    {  

     printf("%s\n",n); 

    } 

return 0; 

} 
+2

移动打印到第一循环? –

回答

0

您可以将名称存储在指向char的指针数组中。

int a; 
printf("enter the number of students:\n"); 
scanf("%d",&a); 

char *n[a]; // VLA; A C99 feature 
// Allocate memory for all pointers. 
for(int i=0;i<a;i++) 
{ 
    n[i] = malloc(50); 
} 
printf("enter the names of the students\n"); 
for(int i=0;i<a;i++) 
{ 
    scanf("%s",n[i]); 
} 

,然后打印出来作为

for(i=0;i<a;i++) 
{  

注:不要使用scanfgets读取字符串。最好使用fgets函数。

fgets(n[i], 50, stdin); 
+0

@self:请参阅编辑。 – haccks

0

只打印最后一个,因为每个人会覆盖掉前一个n内容。你可以在阅读后立即打印出来。

变化

for(i=0;i<a;i++) 
{ 
    scanf("%s",n); 
} 

for(i=0;i<a;i++) 
{  

    printf("%s\n",n); 

} 

for(i=0;i<a;i++) 
{ 
    scanf("%s",n); 
    printf("%s\n",n); 
} 
3

char n[50]是一个字符数组,可以存储多达50大小 在这里,你再次和覆盖相同的字符串只是一个字符串再次与您的scanf

+0

阿琼可以ü请编辑我的程序,请不要让我知道兄弟 –

+1

@ R.A你将如何学习而不为自己思考? – this

+0

阿琼可以建议我一个网站的C? –

1

每当您读取新名称时,都会覆盖最后一个名称。为了避免这种情况,您必须声明一个数组来存储它们。但是,由于您的学生人数是从用户输入中收到的,因此您必须动态分配它,例如,

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 
int main() 
{ 
    int a; 
    int i; 
    char **n; 
    printf("enter the number of students:\n"); 
    scanf("%d",&a); 

    n = malloc(sizeof(char*) * a); 

    printf("enter the names of the students\n"); 

    for(i=0;i<a;i++) 
    { 
     n[i] = malloc(sizeof(char) * 50); 
     scanf("%s",n[i]); 
    } 

    for(i=0;i<a;i++) 
    {  
     printf("%s\n",n[i]); 
    } 

    for(i = 0;i < a;i++) { 
     free(n[i]); 
    } 

    free(n); 

    return 0; 
} 

请避免使用malloc.h。改为使用stdlib.h

+0

'sizeof(char *)'???这有效吗?
错误:无效转换从'void *'到'char **'[-fpermissive] n = malloc(sizeof(char *)* a);' – KNU

+0

@KunalKrishna请参阅http://ideone.com/7DODt7 – Mauren

+1

k,我得到这个错误因为我有C++作为ideone上的语言。这应该是被接受的答案。 – KNU

0

替代,但效率较低回答Mauren的。 我张贴,以帮助您了解其他可能性。

#include<stdio.h> 
#include<string.h> 
#include<stdlib.h> 

#define MAXLEN 50 /*..max #character each name can have*/ 
#define MAXLINES 5000 /*..max #lines allowed*/ 

int main() 
{ 
int a; 
int i; 
char *n[MAXLINES]; //pointer to text lines 
printf("enter the number of students:\n"); 
scanf("%d",&a); 

printf("enter the names of the students\n"); 

for(i=0;i<a;i++){ 
    n[i] = malloc(sizeof(char) * MAXLEN); 
    //same as : *(n+i) = malloc(sizeof(char) * 50); 
    scanf("%s",n[i]); 
} 

for(i=0;i<a;i++){  
    printf("%s\n",n[i]); 
} 

for(i = 0;i < a;i++){ 
    free(n[i]); 
} 

free(n); 
system("pause"); 
return 0; 
} 

推荐阅读:Pointer Arrays; Pointers to Pointers