0

whenever I call this function it fails to give the use a chance to enter the string. Not sure why pretty sure my syntax is spot on. think I has something to do with the newline but I don't know how to get rid of it

 void serchName(dealers_t *ptr, int numDealers) { char dealerName[NAME_LEN]; int index; printf("please enter the dealer's name:"); fgets(dealerName, sizeof(dealerName), stdin); system("PAUSE"); for (index = 0; index < numDealers; index++, ptr++) { if (strcmp(dealerName, ptr->name) == 0) { printf("MATCH FOUND:%s\n%s\n%s\n%i\n%s\n", ptr->name,ptr->city,ptr->state,ptr->zip,ptr->phone); } } } 
7
  • 1
    You have something in stdin from before the call. Make sure you don't. Commented Apr 30, 2014 at 20:15
  • 1
    fflush(stdin); perhaps? Commented Apr 30, 2014 at 20:23
  • 3
    @Jim Only if you want undefined behaviour. Commented Apr 30, 2014 at 20:23
  • scanf("%c%*c", &ch); /* to avoid flushing stdin */ Commented Apr 30, 2014 at 20:31
  • 2
    Fgets also reads the terminal '\n' into the buffer, so the strcmp() will fail (unless the ptr->name also has an '\n' at its end) Commented Apr 30, 2014 at 21:22

1 Answer 1

1

You certainly have some '\n' left-over from previous I/O activity.

It is best to use fgets() and not mixed with scanf() in the same program.

But since I can not see the other code, suggest the following to consume a left-over '\n'.

printf("please enter the dealer's name:"); int ch; ch = fgetc(stdin); if (ch != '\n') ungetc(ch, stdin); if (fgets(dealerName, sizeof(dealerName), stdin) == NULL) Handle_EOForIOError(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.