2

How would I read in exactly 50 characters (49, +1 for null), from a user's input in the console, ignoring only all initial whitespace (as in before the first word) but keeping exactly 49 characters after that, including all whitespace?

Also, if the user were to enter less than 49 characters and enter a newline instead, it would just process that (everything up to the newline ignoring initial whitespace).

I tried to use:

char name[50];
scanf("%49s",name);

However, this seems to ignore all whitespace; so, if my name were to be like: "Mark Smith" it would not process it correctly.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
MrSlime
  • 21
  • 1

1 Answers1

5

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:

  1. Never use (or attempt to use) fflush(stdin).
  2. Code like the following is a typical way:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • For some reason, with that, if my input is over 50 characters it just fails and causes unknown errors in my code. It should just cut off any excess. Any ideas? – MrSlime Mar 10 '22 at 20:50
  • @MrSlime Yes - any excess character will be left in the input buffer, and those may mess up subsequent `scanf` operations. I'll edit in a brief mention of this and a link to the fix ... – Adrian Mole Mar 10 '22 at 20:52
  • I figured it out just from you mentioning that, thank you – MrSlime Mar 10 '22 at 20:59