How to Read a Single Character from the User

Reading a single character in C

scanf("%c",&in);

leaves a newline which is consumed in the next iteration.

Change it to:

scanf(" %c",&in); // Notice the whitespace in the format string

which tells scanf to ignore whitespaces.

OR

scanf(" %c",&in);
getchar(); // To consume the newline

How to read a single character from the user?

Here's a link to the ActiveState Recipes site that says how you can read a single character in Windows, Linux and OSX:

    getch()-like unbuffered character reading from stdin on both Windows and Unix

class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()

def __call__(self): return self.impl()


class _GetchUnix:
def __init__(self):
import tty, sys

def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch


class _GetchWindows:
def __init__(self):
import msvcrt

def __call__(self):
import msvcrt
return msvcrt.getch()


getch = _Getch()

C - Is there a way to read a single character of user input, and not have the rest pushed down to the next request for input?

You are using fgets which is good, but unfortunately not the right way...

fgets reads up to an end of line or at most 1 less the the number of character asked. And of course remaining characters are left for the next read operation...

The idiomatic way would be to ensure reading up to the end of line, whatever the length, or at least up to a much larger length.

  1. Simple but could fail in more than SIZE characters on input:

    #define SIZE 64
    ...

    void read_guess(char *guesses, char *p_current_guess)
    {
    char line[SIZE];
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
    printf(">>> ");
    fgets(line, SiZE, stdin); // read a line of size at most SIZE-1
    p_current_guess[0] = line[0]; // keep first character
    p_current_guess[1] = '\0';
    ...
  2. Robust but slightly more complex

    /**
    * Read a line and only keep the first character
    *
    * Syntax: char * fgetfirst(dest, fd);
    *
    * Parameters:
    * dest: points to a buffer of size at least 2 that will recieve the
    * first character followed with a null
    * fd : FILE* from which to read
    *
    * Return value: dest if one character was successfully read, else NULL
    */
    char *readfirst(dest, fd) {
    #define SIZE 256 // may be adapted
    char buf[SIZE];
    char *cr = NULL; // return value initialized to NULL if nothing can be read
    for (;;) {
    if(NULL == fgets(buff, sizeof(buff), fd)) return cr; // read error or end of file
    if (0 == strcspn(buff, "\n")) return cr; // end of file
    if (cr == NULL) { // first read:
    cr = dest; // prepare to return first char
    dest[0] = buff[0];
    dest[1] = 0;
    }
    }
    }

    You can then use it simply in your code:

    void read_guess(char *guesses, char *p_current_guess)
    {
    int valid_guess = 0;

    // Repeatedly takes input until guess is valid
    while (valid_guess == 0)
    {
    printf(">>> ");
    fgetfirst(p_current_guess, stdin);

How to read a single character with getchar in C?

How to read a single character with getchar in C?

You can read ONLY a single character using getchar.

I have to ask for user input, then use only the first character of the input in my program.

You can do that by reading an entire line and using only the first character of the line.

char line[100]; // Make it large enough.
while( fgets(line, 100, stdin) != NULL )
{
uppercase(line);
char selection = line[0];

switch (selection)
{
...
}
}

How to read a single character from input as u8?

Reading just a byte and casting it to i32:

use std::io::Read;

let input: Option<i32> = std::io::stdin()
.bytes()
.next()
.and_then(|result| result.ok())
.map(|byte| byte as i32);

println!("{:?}", input);

How to read a single character from stdin

strangely enough I can't find a proper duplicate.

#include <iostream>
int main(int argc, char **argv)
{
char c;
std::cin >> c;
std::cout << "this is the char I got: " << c << "\n";
return 0;
}

compile your program with

$ g++ main.cpp -o main

and then run it:

$ ./main
+
this is the char I got: +

How to read a single char from the console in Java (as the user types it)?

What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.

Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:

If your program must be console based,
you have to switch your terminal out
of line mode into character mode, and
remember to restore it before your
program quits. There is no portable
way to do this across operating
systems.

One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.

Read single character with Scanner

There are two ways to do that:

char c = scanner.nextLine().charAt(0);

Which will read the first available line, and extract the first character, or

try {
char c = (char) System.in.read();
} catch (IOException e) {
e.printStackTrace();
}

Which will read the first byte in the first available line and cast it to a char



Related Topics



Leave a reply



Submit