iscntrl() function in C++


The iscntrl() function in C++ checks if a character is a control character or not. This function is defined in ctype.h.

The syntax for iscntrl() function is given as follows −

int iscntrl ( int ch );

Here, ch is the character that needs to be checked.

A program that demonstrates iscntrl() function by counting the number of control characters in a string is given as follows −

Example

 Live Demo

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

using namespace std;
int main() {
   char str[] = "Coding\tis\tfun\n";
   int i, count = 0;

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

Output

The output of the above program is as follows −

Number of control characters in the string are 3

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 control 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\tis\tfun\n";
int i, count = 0;
for(i=0; str[i]!='\0';i++) {
   if(iscntrl(str[i]))
   count++;
}
cout<<"Number of control characters in the string are "<<count;

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

Example

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

using namespace std;
int main() {
   char ch1 = 'A';
   char ch2 = '\n';

   if(iscntrl(ch1))
   cout<<"ch1 is a control character"<<endl;

   else
   cout<<"ch1 is not a control character"<<endl;

   if(iscntrl(ch2))
   cout<<"ch2 is a control character"<<endl;

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

Output

The output of the above program is as follows −

ch1 is not a control character
ch2 is a control character

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

char ch1 = 'A';
char ch2 = '\n';

if(iscntrl(ch1))
cout<<"ch1 is a control character"<<endl;

else
cout<<"ch1 is not a control character"<<endl;

if(iscntrl(ch2))
cout<<"ch2 is a control character"<<endl;
else
cout<<"ch2 is not a control character"<<endl;

Updated on: 25-Jun-2020

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements