-1
int main() {
    char a[100];

    printf("\nEnter 1st Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 1 : %s", a);

    printf("\nEnter 2nd Sentence : ");
    scanf("%[^\n]", a);
    printf("\nSentence 2 : %s", a);

    return 0;
}

My output:

Enter 1st Sentence : Testing 1st Sentence
Sentence 1 : Testing 1st Sentence
Enter 2nd Sentence : 
Sentence 2 : Testing 1st Sentence

I'm basically checking %[^\n]. When I type the 1st sentence and press "Enter" key, it prints "Enter 2nd Sentence : " and then "Sentence 2 : " and then it prints the 1st sentence.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • I would recommend reading this: http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html – babon Sep 19 '17 at 14:53

3 Answers3

4

Because you did not read the Enter key from the input buffer, it is still there when the second scanf() asks for input. It then thinks you just pressed enter without typing any text.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
4

Instead of scanf("%[^\n]", a), use this:

fgets(a, sizeof(a), stdin);

And just strip the trailing newline yourself.

user3386109
  • 34,287
  • 7
  • 49
  • 68
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

There are multiple problems with scanf("%[^\n]", a):

  • You have a potential buffer overfow if reading a line longer than 99 bytes. You can prevent this with scanf("%99[^\n]", a).

  • You leave the newline in the input stream and it is still present for the next call where it causes the conversion to fail because the format must match at least one byte different from newline. You can prevent this by ignoring leading white space with scanf(" %[^\n]", a). Note the initial space in the format string.

  • You do not check if the conversion was successful. scanf() return the number of successful conversions. In your case it should return 1.

Here is the modified program:

#include <stdio.h>

int main(void) {
    char a[100];

    printf("\nEnter 1st Sentence: ");
    if (scanf(" %99[^\n]", a) != 1)
        return 1;
    printf("\nSentence 1 : %s", a);

    printf("\nEnter 2nd Sentence : ");
    if (scanf(" %99[^\n]", a) != 1)
        return 1;
    printf("\nSentence 2 : %s", a);

    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189