Logo Webdesign, Anwendungsentwicklung, Linux-Kickstart

Postalisch

ODT Export PDF Export

Reading single-character

define this function for cutting every following ‚\n‘

#include <stdio.h>
void drain_stdin (void)
{
  int c;
  do
  {
    c = fgetc(stdin);
  } while (c != EOF && c != '\n');
}

example use with scanf() for a char. now the while-loop isn’t executed twice while ENTERing a character.

int main(void)
{
  char x = 1;
  while (x != '0')
  {
    printf( "Enter a char or '0' to exit: " );
    scanf( "%c", &x );
    drain_stdin();
    printf( "The input was: %c\n\n\n", x);
 }
 return 0;
}

Reading string

same problem sollution as above, but now with a string. this one avoids the dangerous gets() function and cut away the input-following ‚\n‘ read-in by fgets()

size_t len;
char buffer[1024];
fgets(buffer, sizeof(buffer), stdin);
len = strlen(buffer);
if(buffer[len - 1] == '\n') buffer[len - 1] = 0;

Links

 
code/ansi_c/snipplets/reading_a_single_character.txt · Zuletzt geändert: 2010/12/10 01:26 (Externe Bearbeitung)
Pragmatisch für Ihre Freiheit!