Hack-R
Hack-R

Reputation: 23231

Dealing with whitespace in scanf and printf

I'm trying to come up with a C program that can accept whitespace in scanf and printf such as a first and last name, as part of a self-learning text I'm reading.

I'm well-aware of buffer overflow potentiality and such security issues with these basic/old functions, but this is strictly for learning purposes, so I do need to stick to them.

My program looks like:

#include <stdio.h>
#include <conio.h>

int main(void)
{
    char name[30];

    printf("Type your name\n");

    scanf("%10[0-9a-zA-Z]", name);

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

and after compilation is able to read in the string with a whitespace, but I can only print the first chunk of text:

C:\Users\hackr>g++ -o whitespace.exe whitespace.c

C:\Users\hackr>whitespace.exe
Type your name
John Doe
John

C:\Users\hackr>

Upvotes: 0

Views: 164

Answers (2)

Arun A S
Arun A S

Reputation: 7026

Try this instead

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

This will read till a newline is encountered.

Upvotes: 1

Patrick Roberts
Patrick Roberts

Reputation: 51956

scanf("%29[0-9a-zA-Z ]", name);
                    ^

You forgot to add a space to the accepted characters in your regex. Also, if your buffer is 30 bytes, you should accept 29 characters, not 10. Leave room for the NUL character.

Another thing to note is that the next time you read from stdin, it will read the characters in that line that weren't within the first 29 characters of that scanf before it begins reading the input from the next prompt. In order to fix that, add this after the scanf:

while (getchar() != '\n')
    ; // read input to end of line

This will always work since '\n' is not in your accepted characters for the regex so it will be left in the stdin buffer.

Upvotes: 2

Related Questions