0

I am currently attempting to obtain a user character input which proceeds a user non-character input, such as integer, float/double, etc. I've read several Stack overflow solutions, and not a single one seems to work for me. Here are the six different ways I attempted to write this code:

#include <stdio.h>
int main(void)
{
  int integer;
  char character;
  scanf("%d", &integer);
  fflush(stdin);
  scanf("%c", &character);
  printf("The ASCII Code of %c is %d", character, character);

This gave an ASCII Code of 10 (\n, i.e. line feed character) implying fflush(stdin) did not flush the line feed whitespace. Then, from this, it would be more relevant and convenient if we looked at lines 7-8. Now, I deleted fflush(stdin) and added a space before %c conversion specifier in scanf(), i.e. scanf(" %c", &character) This also did not work, thus I tried the following: scanf("%c\n", &character) This did allow me to input a value, unlike the previous scenarios, albeit the character was not the same as that inputted because the ASCII code generated was still 10. I also attempted to manipulate the code using getchar() but the ASCII code was either 0 or 10 (space or line feed) and not the actual character input. Thus, I would very much appreciate it if anyone knows a way to resolve this issue. Thank you!

Chronollo
  • 322
  • 1
  • 9
  • 2
    `fflush(stdin)` is undefined behaviour. – Sourav Ghosh Sep 25 '18 at 10:32
  • `scanf("%c", &character);` --> `scanf(" %c", &character);` – Sourav Ghosh Sep 25 '18 at 10:33
  • @SouravGhosh I am aware of that as I read it from previous solutions, hence the other solutions outlined in the post. Also, I already tried that if you read the whole post, it's included. – Chronollo Sep 25 '18 at 10:34
  • Then check the returned value of `scanf()` before proceeding. – Sourav Ghosh Sep 25 '18 at 10:35
  • Yes, but it does not reproduce teh problem you say, – Sourav Ghosh Sep 25 '18 at 10:36
  • 1
    @SouravGhosh Alright, for some reason, the solution you proposed did not yield the desired outcome when I initially tried it, but it seems like it's working now. Although, in my current programming course, we're advised to use fflush(stdin), even though it doesn't work for the most basic user-input code-block. Anyway, thanks for your help! – Chronollo Sep 25 '18 at 10:47
  • [How to read / parse input in C? The FAQ](https://stackoverflow.com/questions/35178520/how-to-read-parse-input-in-c-the-faq) – Lundin Sep 25 '18 at 10:52

0 Answers0