Sie befinden sich hier: Krischer.org » Code » Ansi C » Snipplet Overview » Reading single-character

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

 
Nach oben
code/ansi_c/snipplets/reading_a_single_character.txt · Zuletzt geändert: 2009/01/14 23:48 (Externe Bearbeitung)
edv-krischer.de Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0