简体   繁体   中英

How To Print And Read Strings From stdio

I need to know how to read input from and print answers to the user. How do I go about doing this using char arrays?

This the code I am working with

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]);
}

This is ok:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM