1

How can I input 2 strings which are separated by a new line?

My Problem:

First I need to give how many strings I need to get and then I need to get those strings then display it.

I tried this:

Code:

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

int main()
{

    int n,i = 0;
    scanf("%d", &n);
    char arr[n][100];
    for(int i = 0; i < n; i++)
    {
        scanf("%[^\n]s", arr[i]);
    }

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

    return 0;
}

My Input is :

2 I am
Aravind

My Output is:

I am
þ

First Line I got correct one but second line it shows some garbage value. Help me to solve this.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Aravind Ekan
  • 27
  • 1
  • 6

3 Answers3

7

You have two major problems:

  1. The "%[" format ends with the closing "]", there should be no "s" at the end.

  2. The "%[" format doesn't skip leading space, like that newline which will be present after the first line you read.

Both these issues can be easily solve by using fgets to read whole lines instead.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You already have suggestions to not use scanf. However, if you 'must' use scanf then you can consider the following approach:

  • For dynamic memory allocation you should use malloc
  • the newline character stays in the stdin and hence needs to be flushed or handled/ignored

Here is the updated code.

int main()
{
    int n,i = 0;
    scanf("%d", &n);

    scanf("%*[\n]"); 
    /*this will read the \n in stdin and not store it anywhere. So the next call to 
     * scanf will not be interfered with */

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

    for (i = 0; i < n; i++)
    {
       inputs[i] = malloc(100 * sizeof(char));
    }


    for(i = 0; i < n; i++)
    {
        scanf("%*[\n]");
        scanf("%100[^\n]", inputs[i]);
    }

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

    return 0;
}
Nathalia Soragge
  • 1,415
  • 6
  • 21
-2

use gets(arr[i]) instead of scanf.

new_learner
  • 131
  • 10
  • 2
    Never *ever* use `gets`. [It's a dangerous function](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used), and has therefore been removed from the C standard (and was deprecated long before). – Some programmer dude Jul 17 '18 at 13:05