isspace() function in C++


The isspace() function is a predefined function in ctype.h. It specifies whether the argument is a whitespace character or not. Some of the whitespace characters are space, horizontal tab, vertical tab etc.

A program that implements isspace() function by counting the number of spaces in a string is given as follows −

Example

 Live Demo

#include <iostream>
#include <ctype.h>

using namespace std;
int main() {
   char str[] = "Coding is fun";
   int i, count = 0;

   for(i=0; str[i]!='\0';i++) {
      if(isspace(str[i]))
      count++;
   }

   cout<<"Number of spaces in the string are "<<count;
   return 0;
}

output

The output of the above program is as follows −

Number of spaces in the string are 2

In the above program, first the string is defined. Then a for loop is used to check each of the characters in the string to see if they are a white space character. If they are, then count is incremented by 1. Finally, the value of count is displayed. This is displayed in the following code snippet −

char str[] = "Coding is fun";
int i, count = 0;

for(i=0; str[i]!='\0';i++) {
   if(isspace(str[i]))
   count++;
}
cout<<"Number of spaces in the string are "<<count;

This is another program to demonstrate the isspace() function. It specifies if the given character is a whitespace character or not. The program is given as follows −

Example

 Live Demo

#include <iostream>
#include <ctype.h>

using namespace std;
int main() {
   char ch1 = 'A';
   char ch2 = ' ';
   if(isspace(ch1))
   cout<<"ch1 is a space"<<endl;

   else
   cout<<"ch1 is not a space"<<endl;
   
   if(isspace(ch2))
   cout<<"ch2 is a space"<<endl;

   else
   cout<<"ch2 is not a space"<<endl;
   return 0;
}

Output

The output of the above program is as follows −

ch1 is not a space
ch2 is a space

In the above program, ch1 and ch2 are defined. Then isspace() is used to check if they are whitespace characters or not. The code snippet for this is given as follows −

char ch1 = 'A';
char ch2 = ' ';

if(isspace(ch1))
cout<<"ch1 is a space"<<endl;

else
cout<<"ch1 is not a space"<<endl;

if(isspace(ch2))
cout<<"ch2 is a space"<<endl;

else
cout<<"ch2 is not a space"<<endl;

Updated on: 25-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements