0

I am trying to read just one character but my loop continues to grab the key entered and the 'enter' key. How do I keep that from happening and only grab the first key? Here is an example:

#include <stdio.h>
#include <iostream>
#include <fstream>

using namespace std;

int rseed = 1448736593;

int main(int argc, char** argv) {

    printf("#Program started successfully with random seed %i\n", rseed);

    int c;
    while(true) {
        printf("input: ");
        c = getchar();
        printf("You selected %i\n", c); 
    }   
    return 0;
}

and here is what the code gives:

#Program started successfully with random seed 1448736593
input: 2
You selected 50
input: You selected 10
input: 3
You selected 51
input: You selected 10
input: 1
You selected 49
input: You selected 10
input: ^C

How do I keep it from also telling me that I selected 10? I want to reserve that for when the user just hits 'enter' and nothing else.

drjrm3
  • 4,474
  • 10
  • 53
  • 91
  • Take a look at http://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar – DWright Nov 29 '15 at 23:38
  • http://www.cplusplus.com/reference/cstdio/getchar/ doesn't care what character you input, so it dutifully reports the enter as a newline. – Josh Nov 29 '15 at 23:39
  • Pressing Enter is a character – M.M Nov 30 '15 at 00:11

3 Answers3

1

The second value you get (10 - decimal ASCII code for newline / line feed) is because of the newline character resulted from Enter press.

Easiest way to solve this:

c = getchar();
if (c != '\n') // or (c != 10)
    getchar(); // call again getchar() to consume the newline
printf("You selected %i\n", c); 

Now the output is:

input: 2
You selected 50
input: 3
You selected 51
input:              // <- Enter alone was pressed here
You selected 10
input: 1
You selected 49
input: ^C

But the case when the user inputs multiple characters before pressing Enter is unhandled here, every second character will be ignored in that case.

nnn
  • 3,980
  • 1
  • 13
  • 17
0

char c= getchar();

When control is on above line then getchar() function will accept the single character. After accepting character control remains on the same line. When user presses the enter key then getchar() function will read the character and that character is assigned to the variable ‘c’.

-1

To ignore newline characters:

int getchar2(void) {
  int ret;
  do {
    ret = getchar();
  } while (ret == '\n');
  return ret;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70