Home > OS >  How can I introduce multiple strings with scanf() in the easiest way?
How can I introduce multiple strings with scanf() in the easiest way?

Time:10-11

How can I introduce multiple strings in input and output with scanf()? Is it possible to do that without using 100 notations (e.g. a, b, c, d, e -> "%c %c %c", a, b, c etc.)? I type this:

#include <stdio.h> 
int main()
{
    char user_str[20];
    scanf("%s", user_str);
    printf("%s", user_str);
    return 0;
}

Which works for the first word as input and output, but if I want to introduce 100 propositions with space in the text, how can I type the code to do that in the easiest way possible?

CodePudding user response:

As @Yunnosch notes, your best best is to use loops and arrays. Consider a simple situation where you want to read in 4 strings that are up to 19 characters in length. We have length 20 to leave space for a terminating null character.

#include <stdio.h>

int main() {
    char input[4][20];

    for (int i = 0; i < 4; i  ) {
        scanf("s", input[i]);
    }

    for (int i = 0; i < 4; i  ) {
        printf("%s\n", input[i]);
    }
}

This is readily scalable to 100s of strings. If you use enough memory, you may wish to use malloc to allocate it, but the same basic pattern would continue.

CodePudding user response:

Here is a solution which reads one line of input using scanf:

#include <stdio.h> 
int main()
{
    char user_str[20];
    scanf("%[^\n]s", user_str);
    printf("%s", user_str);
    return 0;
}

Using %[^\n]s instead of %s will read all characters until you reach \n (or EOF ) and write them into user_str. But this solution is worse than gets(), so try to use fgets() instead.

#include <stdio.h>

int main()
{
    char user_str[100];
    printf("Enter your name: ");
    fgets(user_str, 100, stdin); 
    printf("Your Name is: %s", user_str);
    return 0;
}
  •  Tags:  
  • c
  • Related