2

So I'm starting this program, new stage of learning and I need to learn how to only allow the user to input a certain amount of characters when I prompt them to type. So for example:

char firstname[20];
printf("What is your first name?");
scanf("%s", &firstname);

I only want the user to be able to type and enter 20 characters. How would I go about this and would it be the same way when prompting the user to only enter numbers?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 3
    Off topic code comment: if you want 20 characters in a string your array should be 21 characters long (for the null character). – Taelsin Jan 26 '16 at 20:36
  • 2
    What should happen when someone enters more than 20 characters? – Jongware Jan 26 '16 at 20:36
  • There is no way (unless code controls a robotic arm) to prevent a user from typing more than 20 characters. As noted, you need to define what you want to happen when excess characters are typed. Without that info, the question is too broad. – chux - Reinstate Monica Jan 26 '16 at 20:56

4 Answers4

5

I only want the user to be able to type and enter 20 characters

Well, you can only instruct the user and expect them to follow. There is nothing you can do to stop the user from inputting more than n characters, but, programatically, you can only limit the scanning to n characters, using

char firstname[20];
printf("What is your first name?");
scanf("%19s", firstname);           //& not needed

leaving the space for null-terminator.

In case, the name contains a whitespace, %s with scanf() will not be able to handle the input. In that case, you may want to make use of fgets() which can handle the presence of whitespace in the input string.

That said,

  1. You may want to clean up the input buffer of remaining characters after scanning.
  2. Always check for the return value of scanf() to ensure successful scanning.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Consider using fgets :

char *fgets(char *str, int n, FILE *stream)

According to man :

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

Sample snippet :

fgets(firstname,20,stdin);

Remember to remove the trailing newline ('\n') from the string. You can do that using strcspn, just

#include  <string.h>

Also, if your attempt was to make the user able to enter max 20 char you should declare your array with 1 more position, because of the null terminating character '\0'. So it should be

char firstname [21];

Note that fgets() will prevent buffer overflow but will not handle extra characters In fact they are left in stdin. This can be a problem. However I've found this post useful and I will quote the solution to this, posted by BLUEPIXY :

fgets(answer2,sizeof(answer2),stdin);
> if(!strchr(answer, 'n')) //newline does not exist while(fgetc(stdin)!='n');//discard until newline fgets(answer2,sizeof(answer2),stdin);
Community
  • 1
  • 1
Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
2

There are two very different issues here:

  1. How to limit your buffer size and avoid overwriting the end of the buffer

  2. How to deal with a user typing more characters than you expect

Most of the answers already given focus on #1, and they're fine.

For #2, your program must read the extra characters and discard them. You can read them in chunks until you get an end-of-line, for example. If you don't do that, then the extra characters will end up in the input buffer after the next prompt, and your program and the user will be out of synch.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
0

If you want to limit the number of characters the user may type at the console, then you're going to have to use utilities not present in the C language itself. The standard C I/O routines only see an input stream, which isn't updated until after the user types Enter. You might want to look at ncurses, particularly the forms library, for that sort of functionality.

You can limit how much input your program reads from the input stream in a couple of ways. If using fgets, you pass a separate parameter indicating the size of the input buffer:

char buff[N+1]; // where N is the max number of characters you want to allow
if ( fgets( buff, sizeof buff, stdin ) )
{
  // process contents of buff
}

In this code, only sizeof buff - 1 characters are read from the input stream and stored to buff. However, this has no effect on how many characters the user may type in from the console (since fgets blocks until the user hits Enter).

If using scanf, you can use a maximum field width as part of the conversion specifier:

if ( scanf( "%19s", buff ) == 1 )
{
  // process buff
}

Unfortunately, there isn't a good way to pass the field width as an argument to scanf (like you can with printf); it has to be hardcoded as part of the conversion specifier.

John Bode
  • 119,563
  • 19
  • 122
  • 198