C Library - isspace() function



The C library isspace() function checks whether the passed character is white-space.

This function is a part of the C Standard Library, included in the <ctype.h> header.

Standard white-space characters are −

' '   (0x20)	space (SPC)
'\t'	(0x09)	horizontal tab (TAB)
'\n'	(0x0a)	newline (LF)
'\v'	(0x0b)	vertical tab (VT)
'\f'	(0x0c)	feed (FF)
'\r'	(0x0d)	carriage return (CR)

Syntax

Following is the C library syntax of the isspace() function −

int isspace(int c);

Parameters

This function accepts a single parameter −

  • c − This is the character to be checked, passed as an int. The value of c should be representable as an unsigned char or be equal to the value of EOF.

Return Value

The isspace(int c) function returns a non-zero value (true) if the character is a whitespace character. Otherwise, it returns zero (false). The whitespace characters checked by isspace include −

  • Space (' ')
  • Form feed ('\f')
  • Newline ('\n')
  • Carriage return ('\r')
  • Horizontal tab ('\t')
  • Vertical tab ('\v')

Example 1: Checking different input as whitespace

A character 't', a number '1' and a space '' are checked for whitespace recognition using the isspace() function.

#include <stdio.h>
#include <ctype.h>

int main () {
   int var1 = 't';
   int var2 = '1';
   int var3 = ' ';

   if( isspace(var1) ) {
      printf("var1 = |%c| is a white-space character\n", var1 );
   } else {
      printf("var1 = |%c| is not a white-space character\n", var1 );
   }
   
   if( isspace(var2) ) {
      printf("var2 = |%c| is a white-space character\n", var2 );
   } else {
      printf("var2 = |%c| is not a white-space character\n", var2 );
   }
   
   if( isspace(var3) ) {
      printf("var3 = |%c| is a white-space character\n", var3 );
   } else {
      printf("var3 = |%c| is not a white-space character\n", var3 );
   }
   
   return(0);
}

Output

The above code produces following result−

var1 = |t| is not a white-space character
var2 = |1| is not a white-space character
var3 = | | is a white-space character

Example 2: Newline Character

This example checks if the newline character ('\n') is a whitespace character. Since it is, the function returns true.

#include <stdio.h>
#include <ctype.h>

int main() {
   char ch = '\n';
   if (isspace(ch)) {
      printf("The character is a whitespace character.\n");
   } else {
      printf("The character is not a whitespace character.\n");
   }
   return 0;
}

Output

After execution of above code, we get the following result −

The character is a whitespace character.
Advertisements