Search code examples
cinputoutputuser-input

Why does the presence of `n` in the input sentence before `\n` give wrong output?


I want to input a sentence (containing any possible characters) and print it. But there is a catch. If there is a \n in the sentence then only the part of the sentence before \n should be printed out (i.e. \n should signify the end of the inputted sentence). I wrote a code for this situation :

#include <stdio.h>
main()
{
    char ch[100];
    printf("Enter a sentence");
    scanf("%99[^\\n]",&ch);
    printf("%s",ch);
}

This code seems to work fine but it fails in a certain situation. If there is the character n anywhere in the sentence before \n then it prints only the first word of the sentence! Why does this happen? How can I fix this bug?

This case works fine: enter image description here

But in this case it fails:

enter image description here


Detail from comments:

Q: Do you want to to stop at a newline, or at a backslash followed by n?
A: slash followed by n


Solution

  • The [] conversion specifier of scanf() works by defining an accepted (or, with ^, rejected) set of characters. So %[^\\n] will stop scanning at the first \ or the first n -> You can't solve your problem with scanf().

    You should just read a line of input with fgets() and search for an occurence of "\\n" with strstr().


    Side note: there's an error in your program:

    char ch[100];
    scanf("%99[^\\n]",&ch);
    

    ch evaluates as a pointer to the first element of the array (so, would be fine as parameter for scanf()), while &ch evaluates to a pointer to the array, which is not what scanf() expects.

    (the difference is in the type, the address will be the same)