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.

0

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi is there any other method apart from fgets?
@AravindEkan To read lines using standard C functions only, the best solution is fgets. You can use scanf (and family) but it becomes much more complex, and without a field-width limiter can also easily cause buffer overflows.
3rd problem, no width limit. "%[^\n]" is then akin to gets(). Yes, better to use fgets().
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;
}

Comments

-2

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

1 Comment

Never ever use gets. It's a dangerous function, and has therefore been removed from the C standard (and was deprecated long before).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.