Home > Enterprise >  Printf display only one word
Printf display only one word

Time:03-02

I want to display more than one word using printf, Do I should change first parameter in pritnf?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>



int main() {
    
    int value;
    printf("How many:"); scanf("%d", &value);

    char* arr1 = new char[value];

    scanf("%s[^\n]", arr1);

    printf("%s", arr1);

    delete [] arr1;
    return 0;
}

CodePudding user response:

As already pointed out in the comments section, the following line is wrong:

scanf("%s[^\n]", arr1);

The %s and %[^\n] are distinct conversion format specifiers. You seem to be attempting to use a hybrid of both. If you want to read a whole line of input, you should use the second one.

However, even if you fix this line, your program will not work, for the following reason:

The statement

scanf("%d", &value);

will read a number from standard input, but will only extract the number itself from the input stream. The newline character after the input will not be extracted.

Therefore, when you later call

scanf("%[^\n]", arr1);

it will extract everything that remained from the previous scanf function call up to the newline character. This will result in no characters being extracted if the newline character immediately follows the number (which is normally the case).

Example of program's behavior:

How many:20ExtraInput
ExtraInput

As you can see, everything after the number up to the newline character is being extracted in the second scanf function call (which is then printed). However, this is not what you want. You want to extract everything that comes after the newline character instead.

In order to fix this, you must discard everything up to and including the newline character beforehand. This must be done between the two scanf function calls.

#include <stdio.h>

int main()
{    
    int value;
    int c;

    printf("How many:"); scanf("%d", &value);

    char* arr1 = new char[value];

    //discard remainder of line, including newline character
    do
    {
        c = getchar();

    } while ( c != EOF && c != '\n' );

    scanf("%[^\n]", arr1);

    printf("%s", arr1);

    delete [] arr1;
    return 0;
}

The program now has the following behavior:

How many:20ExtraInput
This is a test.
This is a test.

As you can see, the program now discards ExtraInput and it correctly echoes the line This is a test.

  •  Tags:  
  • c
  • Related