Isspace() function in C++ with an example

Hi guys, today we try to see what is the isspace() in C++.

When we insert a string into the system, it may or may not have spaces among them. So if we need to check if such kinds of whitespaces are available, then we check for it using this function.

C++ has various kinds of whitespaces as:

  • Space
  • Horizontal tab
  •  Newline
  •  Vertical tab
  •  Feed
  • Carriage return

This function can be invoked by the <string> header file, or we can also use the <bits/stdc++> header file for universal call.

Let us see the application of this function by an example.

#include <bits/stdc++.h> 
using namespace std; 

void check(string& s) 
{ 
  int c = 0; 
   
  for (int i = 0; i < s.length(); i++) { 
    if (isspace(s[i])) 
      c++; 
  } 
  cout <<"\n No.of spaces is- " <<c; 
}

We declare a function to check for spaces. We take in the string, and check each letter one by one using the isspace(). If found, we increment a variable.

Now we declare the main().

int main() 
{ 
  string s = "Welcome to Codespeedy"; 
  check(s); 
  return 0; 
}

We get the result as:

 No.of spaces is- 2
--------------------------------
Process exited after 2.625 seconds with return value 0
Press any key to continue . . .

I hope this tutorial was useful for your knowledge.

Also read: How to check if a given number is Fibonacci number in C++

Leave a Reply

Your email address will not be published. Required fields are marked *