Finley Adams
Finley Adams

Reputation: 831

Recognize "space" and "enter" with scanf C

I need to recognize if a character taken as input is SPACE or ENTER. I know that enter is "0x0A" as hexadecimal while space is "0x20" but I don't kown why scanf seems to not recognize space.

while ( (error=scanf("%d", &stop) )== EOF && error==0 )
  printf("Error while reading the value input, try again\n");
...(some code)...
while ( stop!= 0x0A )
{
    if (stop == 0x20) {
        printf("Going to fill the line\n");
    ...(some code)...
 }

With the 1st "while" I want that the user inserts a generic value, in the 2nd I check if the value was "ENTER" and the "if" checks if "SPACE" has been inserted. If I press "SPACE" there's a segmentation fault, don't know why :S

EDIT :

I wrote this new example from what I read in comments :

#include <stdio.h>
#include <stdlib.h>

void main()
{
    char input;
    int error =0;
    printf("I want to read only numbers\n" 
        "Let's start!\n");
    while ( (error=scanf("%c", &input) )== EOF || error==0 )
        printf("Error while reading the input, maybe Enter was pressed try again\n");
        printf("input is : %c \n",input);
        printf("Taking new input : \n");
   while (input != "\n")
   {
       if (input == 0x20)
          break;
          printf("Taking New input : \n");
       while ( (error=scanf("%c", &input) )== EOF || error==0 )
        printf("Error while reading the input, maybe Enter was pressed try again\n");
        printf("New input is : %c \n",input);
   }
   return;
}

this is the output :

I want to read only numbers
Let's start!
7
input is : 7 
Taking New input : 
New input is : 

And the program ends.

Upvotes: 2

Views: 961

Answers (1)

chux
chux

Reputation: 154315

why scanf seems to not recognize space.

scanf() can recognized spaces, but not readily using scanf("%d", &stop) as "%d" first consumes and discards all leading white-space.

"%c" does not discard leading whitespace. One character is read.


As OP seems interested in reading and testing a single character one at a time using scanf(), along with detecting a rare input error and maybe end-of-file:

// Read one character.
// Return 1 on success.
// Return EOF on end-of-file.
// Return 0 on rare input error.
int read1(char *dest) {
  if (scanf("%c", dest) == 1) return 1;
  if (feof(stdin)) return EOF;
  return 0;
}

need to recognize if a character taken as input is SPACE or ENTER

fgets() is a much better approach to read a line of user input.

char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
  // Use buf
}  

Upvotes: 1

Related Questions