如何使用for循环打印输入的字符串?

时间:2014-03-13 13:44:56

标签: c string for-loop

我是C编程的新手,我不知道如果我编译这段代码,我可以在这段代码中更改什么,它只显示n次的姓氏..为什么它不会显示其他名称请高手帮忙..谢谢!

#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;

}

5 个答案:

答案 0 :(得分:3)

char n[50]是一个字符数组,只能存储一个最大为50的字符串。 在这里,您使用scanf一次又一次地覆盖相同的字符串。

答案 1 :(得分: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

答案 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);

答案 3 :(得分: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);
}

答案 4 :(得分: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

相关问题