0

My program uses a scanf as such:

scanf ("%c", &symbol);

is there a way to print an error if the user enters in a string > one character? e.g "abc" as it messes with the program later on

user3311792
  • 21
  • 1
  • 1
  • 3
  • There is not "a" way to do this. There are plenty. One of them is to see if there is further input with `getchar()` or something similar (to consume any invalid input). Or just scan a characters sequence with `%s` and then pick the first one. There are so many options, it's hard to tell what would be the best for you without some more context. – Filipe Gonçalves Mar 11 '14 at 18:41
  • This is exactly why you shouldn't use `scanf` in the first place. It's a buffer overflow waiting to happen. – chepner Mar 11 '14 at 18:41
  • @chepner, reading *one* character into a `char` variable using `scanf(3)` can't possibly cause a buffer overrun. – vonbrand Mar 11 '14 at 20:50
  • @vonbrand: Let's play a game: how long has it been since I've programmed in anything more low level than Python? :) I forgot the format string will control how much is read from stdin. – chepner Mar 11 '14 at 21:18

1 Answers1

0

Use a string buffer, fgets() into it, check if the second character is a \n.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31