Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf() doesn't accept whitespace

Tags:

c++

c

scanf

I need a scanf() call to accept whitespace (no tabs or newlines, just ' ' space glyphs).

char buffer[2048];
scanf(" %2048[0-9a-zA-Z ]s", buffer);

This format specifier I got from the answer to this question:

how-do-you-allow-spaces-to-be-entered-using-scanf

While it accepts the first sequence of input just fine, it terminates where the first whitespace character is, with a null character. What's going on? Am I perhaps using the wrong format?

I should say, I'm using scanf() here because safety isn't a concern; I'm the only person who'll ever use this particular program, and the input is rigidly formatted.

like image 890
Anne Quinn Avatar asked Apr 29 '26 10:04

Anne Quinn


1 Answers

Use scanf("%[^\n]",buffer);. It will accept white space.

Sample program-

int main()
{
    char buffer[2048];
    printf("Enter the string\n");
    scanf("%[^\n]",buffer);

    printf("%s\n", buffer);
    return 0;
}

output-

root@sathish1:~/My Docs/Programs# ./a.out 
Enter the string
abc def ghi ijk
abc def ghi ijk
root@sathish1:~/My Docs/Programs# 
like image 89
Sathish Avatar answered Apr 30 '26 22:04

Sathish