CPKEN
CPKEN

Reputation: 11

Why is scanf("%[^\n]s", ...) not capturing a string with spaces?

I've been scouring the globe as to why scanf() is not capturing spaces, and the usual solutions such as "%[^\n]s" or "%100s" (setting string large enough to capture input) have not been working.

The overall goal of my program is to prompt the user to enter a string, and then that string be stored in a .txt file. I don't believe my problem is arising from fprintf(), rather from the initial console scan.

Yes, I am a beginner and do not understand the nuances of C. Apologies for seemingly simple syntactic errors. Here's what I got.

#include <stdio.h>  
  
int main()
{
    errno_t inputfile;
    FILE *stream;

    inputfile = fopen_s(&stream, "inputfile.txt", "w");
    printf("%s", "Enter a string.  Press ENTER to exit\n");

    char c[100];
    scanf("%[^\n]s", c);
    printf("%100s", c); //using printf() to check if scanf() worked.  
                        //Messing around with specifier to see if problem 
                        //is in printf(), which doesn't seem to be the case.

    fprintf(stream, "%s", c);
    fprintf(stream, "%s", "ENTER is a correct ending");
    fclose(stream);

    return 0;
}

Any help is appreciated.

Upvotes: 0

Views: 136

Answers (1)

anastaciu
anastaciu

Reputation: 23802

scanf("%[^\n]s", c); is not correct, remove the s at the end of the specifier, you should also use a width limiter to avoid buffer overflow.

It should be:

scanf("%99[^\n]", c); // leave 1 character for the null byte

Notwithstanding, the behavior you describe is unexpected as you can see here:

https://godbolt.org/z/enq93MaG5

Note that I turned your code in a minimal reproducible example, i.e., I removed the unnecessary code, that's what you should do from now on.

Also note that printf("%100s", c); will have the, perhaps undesired, effect of adjusting your string to the right printing the remaining characters as blank spaces to the left, e.g. a string with 10 characters will print 90 blank spaces and then the string.

Upvotes: 2

Related Questions