What is isblank() in C++?

We use the isblank() function in C++ to determine if a given character is a blank character. A blank character is any of the following characters:

  • ' ': The space character.
  • '\t': The tab character.

Library

To use the isblank() function, include the following library:

#include <cctype>

Declaration

The isblank() function is declared as follows:

int isblank(int c);
  • c: The ASCII value of the character being checked.

Note: If c is not an unsigned char or EOF, the behavior of the isblank() function is undefined.

Return value

  • The isblank() function returns a non-zero value if c is a blank.
  • The isblank() function returns 0 if c is not a blank.

Code

Example 1

Consider the code snippet below, which demonstrates the use of the isblank() function.

#include <cctype>
#include <iostream>
using namespace std;
int main()
{
char c1 = 'a';
char c2 = ' ';
cout<<"'"<<c1<<"' is blank: "<<isblank(c1)<<endl;
cout<<"'"<<c2<<"' is blank: "<<isblank(c2)<<endl;
return 0;
}

Explanation

Two characters c1 and c2 are declared in lines 7-8. c1 is not a blank and c2 is a blank.

  • line 10: We use the isblank() function in line 10 to check whether c1 is a blank. The isblank() function returns 0, which means that c1 is not a blank.
  • line 11: We use the isblank() function in line 11 to check whether c2 is a blank. The isblank() function returns a non-zero value, which means that c2 is a blank.

Code 2

Consider the code snippet below, which uses the isblank() function to remove the blanks from other characters in a string.

#include <cctype>
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char str[] = "H el lo w o r d!! ";
int len = strlen(str);
char withoutBlanks[len];
int blankCount = 0;
int ind = 0 ;
for(int i = 0; i < len; i++){
if( isblank(str[i])==0 ){
withoutBlanks[ind] = str[i];
ind++;
}else{
blankCount++;
}
}
withoutBlanks[ind] = '\0';
cout<<"string = "<<str<<endl;
cout<<"string without blanks = "<<withoutBlanks<<endl;
cout<<"number of blanks in string = "<<blankCount<<endl;
return 0;
}

Explanation

  • line 8: A string str is declared that contains both blank and non-blank characters.
  • line 10: A string withoutBlanks is declared that will contain the non-blank characters of str.
  • line 11: A variable blankCount is declared that will contain the count of the number of blank characters of str.
  • lines 14-17: Loop over the characters of str such that if a character is a non-blank, it is copied the character in withoutBlanks. If a character is a blank, add one to blankCount.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved