You can precede the input format specifier with a (single) space, to skip any/all leading whitespace characters and then use the [set]
format specifier (with a preceding "49" limit) to input all subsequent characters that match the given "set". In your case, that set would be anything except a newline character, so use the "not" prefix (^
) before the set, and make the set consist of just the newline (\n
):
#include <stdio.h>
int main()
{
char name[50];
printf("Enter input: ");
int n = scanf(" %49[^\n]", name);
if (n != 1) {
printf("Input error!");
}
else {
printf("Input was: %s\n", name);
}
return 0;
}
Test:
Enter input: I am the egg-man; I am the egg-man; I am the walrus!
Input was: I am the egg-man; I am the egg-man; I am the walr
Note that, using the above code, if an input string of more than 49 characters is entered, then the excess characters will be left in the input buffer. These will very likely cause problems further down the line, as they will be taken as input to any subsequent calls to scanf
(or similar input functions).
There are several ways to 'clear' the input buffer: How to clear input buffer in C? To give a brief summary of the answers to the linked question:
- Never use (or attempt to use)
fflush(stdin)
.
- Code like the following is a typical way:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }