如何从stdio打印和读取字符串

时间:2012-05-16 02:31:18

标签: c

我需要知道如何从用户那里读取输入并打印答案。我该怎么走 关于使用char数组执行此操作?

这是我正在使用的代码

int array[500];
char array2[200];
printf("Please Enter The number of names: ");
scanf("%d",&num);

for(i=0;i<num;i++){
    array[i]=0;
    array2[i]="";
}
printf("\nPlease Enter names:");
for(i=0;i<num;i++){
    scanf("names: %s",array2[i]);
}
for(i=0;i<num;i++){
    printf("\n %s",array2[i]);
}

1 个答案:

答案 0 :(得分:0)

没关系:

#include <stdio.h>

#define MAX_PEOPLE 128

static inline clear()
{
    while (getchar() != '\n');
}

int main()
{
    int num, i;
    int array[500];
    char array2[MAX_PEOPLE][200];
    printf("Please Enter The number of names: ");

    while (1)
    {
        if (scanf("%d",&num) != 1 || num > MAX_PEOPLE)
        {
            clear();
            printf("Again: ");
            continue;
        }

        break;
    }

    for(i = 0; i < num; i++)
    {
        array[i] = 0;
        array2[i][0] = '\0';
    }

    printf("\n");
    for(i = 0; i < num; i++)
    {
        printf("Please Enter names: ");
        scanf("%s",array2[i]);
    }

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

    return 0;
}