Austin Smith
Austin Smith

Reputation: 35

fgets limiting input length

When I'm inputting data like a last name I have got it so it limits it to 10 characters, but when I try to enter the last name, the characters that were excluded from the first name are put into the last name. For example, if I enter aaaaaaaaaab it will keep the a's but the b will be put into last name.

Any suggestions how I would fix this? I want it to limit the length to the correct amount.

printf("you chose add new record\n"); 
printf("enter the person information: \n");
printf("Please enter the first name: \n");
//limits to size 10
char namein[11];
fgets(namein, 11, stdin);
printf("the first name was: %s\n", namein);

printf("Please enter the last name: \n");
//limits to size 20
char lastin[21];
fgets(lastin, 21, stdin);
printf("the last name was: %s\n", lastin);

Upvotes: 2

Views: 4386

Answers (2)

chux
chux

Reputation: 153338

Examine the result of using fgets().

If the buffer contains a \n, no need to look for more. Otherwise consume potential extra data until '\n' or EOF.

int ConsumeExtra(const char *buf) {
  int found = 0;
  if (strchr(buf, '\n') == NULL) {
    int ch;
    // dispose of extra data
    while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
      found = 1;
    }
  }
  return found;
}

char namein[11];
if (fgets(namein, sizeof namein, stdin) == NULL) Handle_EOForIOError();
if (ConsumeExtra(namein)) Handle_ExtraFound(); 

Note: Recommend not being so small with input buffers. Better to reads into a general large buffer and then qualify the input before saving to namein. IOWs, prefer to keep input and scanning/parsing separate.

char buffer[100]
char namein[11];
if (fgets(namein, sizeof buf, stdin) == NULL) Handle_EOForIOError();
if (ConsumeExtra(buf)) Handle_InsaneLongInput();

int n = 0;
sscanf(buffer, "%10s %n", namein, &n);
if (n == 0 || buf[n]) Handle_NothingOrExtraFound();

Upvotes: 4

Edwin Buck
Edwin Buck

Reputation: 70909

You have to read the entire input buffer before doing the next read. Such an operation is called "draining" the input.

So your code should look like

get the first name
read the first name
drain the input
print the prompt for the last name
read the last name

draining the input looks roughly like

while (there is data that can be read) {
  read a character
}

Upvotes: -1

Related Questions