isspace() in C++ and its application to count whitespace characters

isspace() function
In C++, isspace is a predefined function used for string and character handling.cstring is the header file required for string functions and cctype is the headerfile required for character functions.

This function is used to check if the arguement contains any whitespace characters.
There are many types of whitespace characters in c++ such as-

  • ‘ ‘ – Space
  • ‘\t’ – Horizontal tab
  • ‘\n’ – Newline
  • ‘\v’ – Vertical tab
  • ‘\f’ – Feed
  • ‘\r’ – Carriage return
int isspace(int x)

Given a string, we need to count the number of whitespace characters in the string using isspace() function.


Input : string = 'Geeks for geeks'
Output :2

Input :string = 'My name is Ayush'
Output :3

1. Traverse the given string character by character upto its length, check if character is a whitespace character.
2. If it is a whitespace character, increment the counter by 1, else traverse to the next character.
3. Print the value of the counter.

// CPP program to count white spaces in a string
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

// function to calculate whitespaces
void space(string& str)
    int count = 0;
    int length = str.length();
    for (int i = 0; i < length; i++) {
        int c = str[i];
        if (isspace(c))
    cout << count;

// Driver Code
int main()
    string str = "Geeks for geeks";
    return 0;



This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at to report any issue with the above content.

Recommended Posts:

0 Average Difficulty : 0/5.0
No votes yet.

Writing code in comment? Please use, generate link and share the link here.