0

so my problem is that I need to read integer values from the user, until the character 'o' is entered. I do not know how to differentiate a character from from a number, when reading values from the user.

I wanted to use a do while, it felt pretty natural.

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a;

    do
    {
        scanf("%d", &a);
    } while (a != 'o');
}

but of course I can not use %d for the character that I will enter while the program runs.

So the program should read integers from the user, until a specific character ('o' in this case) is entered. right now, after I input a character it will not read my input, the program will just hang there. Thanks a lot!

Dor Peled
  • 1
  • 1
  • Possible duplicate of [scanf() for Integer OR Character](https://stackoverflow.com/questions/49725845/scanf-for-integer-or-character) – Nellie Danielyan May 03 '19 at 13:35
  • `char a; scanf("%c",&a); printf("%c\n",a);` – Sir Jo Black May 03 '19 at 13:46
  • Will the size be enough if I use a char though? I want any signed integer until I input the character 'o', I will later insert the numbers into a stack by the way, just need to get that part cleared first. thanks – Dor Peled May 03 '19 at 13:51

1 Answers1

0

May not be idea solution but my suggestion is don't use same variable to read integer and character, instead you can use another char variable to read character, if input 'o' it will exit else it will read 'return' char when you hit enter and get read to read next integer. I have modified program bit to do that(as scanf() ignore char 'o', getchar() will read it and then it exits from while loop)

#include <stdio.h>
#include <stdlib.h>

void main()
{
   int a;
   char c;

   do
   {
      scanf("%d", &a);
      c = getchar();
   } while (c != 'o');

 }
ShivYaragatti
  • 398
  • 2
  • 8
  • This might actually work, with the restraints that were given to us by our professor. I would love to see an ideal solution though :D thanks for your solution!! – Dor Peled May 03 '19 at 14:09