-2

I'm trying to read 4 user inputs that can either be one digit, two digits, or a letter. I've tried using %c, but that can't contain any two digit numbers. I've also tried %d, but that reads all letters as 0. Is there anything that can cover all the bases?

  • "but [`%d`] reads all letters as `0`" ... nope: `scanf` returns an error and the associated variable is indeterminate. – pmg Mar 11 '17 at 13:13
  • We are not a coding/trutoring/"do my homework" service. Read [ask], provide a [mcve] with clear and **specific** problem statement what does not work. A character cannot contain two digits, of course. – too honest for this site Mar 11 '17 at 13:21

2 Answers2

2

In C there %c is usually for character inputs and %d is for integer. Usually you use these when scanning. Try %s this scans a string.

Rekt
  • 359
  • 2
  • 18
0

Read a line and store it as a string. Then you can analyze what you got.

Simple example:

  size_t n = 2;
  char *str;
  str = malloc (n + 1);
  getline (&str, &n, stdin);

  if (str[0]>='0'&& str[0]<='9')
    if (str[1]>='0' && str[1]<='9')
      printf("Two digits\n");
    else
      printf("One digit\n");

Note that this is very naive, and contains almost no error detection, but it gives an idea for how to do it.

klutt
  • 30,332
  • 17
  • 55
  • 95
  • 1
    [`malloc` should not be cast](http://stackoverflow.com/q/605845/995714) – phuclv Mar 11 '17 at 13:24
  • @LưuVĩnhPhúc Well it depends, but in most cases you're right. I'll change it. – klutt Mar 11 '17 at 13:32
  • it's not depending on anything. there are no cases that you need to cast the result of malloc in C – phuclv Mar 11 '17 at 13:43
  • I will not go deep into that discussion. It is pretty clearly explained in the link you provided. Thanks for pointing it out. – klutt Mar 11 '17 at 13:49