In C++, iscntrl() is a predefined function used for string and character handling. cstring is the header file required for string functions and cctype is the header file required for character functions. A control character is one which is not a printable character i.e, it does not occupy a printing position on a display.
This function is used to check if the argument contains any control characters. There are many types of control characters in C++ such as:
- Horizontal tab – ‘\t’
- Line feed – ‘\n’
- Backspace – ‘\b’
- Carriage return – ‘\r’
- Form feed – ‘\f’
- Escape
Syntax
int iscntrl ( int c );
Applications
- Given a string, we need to find the number of control characters in the string.
Algorithm
1. Traverse the given string character by character up to its length, check if the character is a control character.
2. If it is a control character, increment the counter by 1, else traverse to the next character.
3. Print the value of the counter.
Examples:
Input : string='My name \n is \n Ayush'
Output :2
Input :string= 'This is written above \n This is written below'
Output :1
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
void space(string& str)
{
int count = 0;
int length = str.length();
for ( int i = 0; i < length; i++) {
int c = str[i];
if ( iscntrl (c))
count++;
}
cout << count;
}
int main()
{
string str = "My name \n is \n Ayush" ;
space(str);
return 0;
}
|
Output:
2
- Given a string, we need to print the string till a control character is found in the string.
Algorithm
1. Traverse the given string character by character and write the characters to the standard output using putchar().
2. Break the loop when a control character is found in the string.
3. Print the final string from the standard output.
Examples:
Input : string='My name is \n Ayush'
Output :My name is
Input :string= 'This is written above \n This is written below'
Output :This is written above
#include <iostream>
#include <cstring>
#include <cctype>
#include<cstdio>
using namespace std;
int space(string& str)
{
int i=0;
while (! iscntrl (str[i]))
{
putchar (str[i]);
i++;
}
return 0;
}
int main()
{
string str = "My name is \n Ayush" ;
space(str);
return 0;
}
|
Output:
My name is
This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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.