iscntrl() in C++ and its application to find control characters
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
// CPP program to count control characters in a string
#include <iostream>
#include <cstring>
#include <cctype>
using
namespace
std;
// function to calculate control characters
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;
}
// Driver Code
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
// CPP program to print a string until a control character
#include <iostream>
#include <cstring>
#include <cctype>
#include<cstdio>
using
namespace
std;
// function to print string until a control character
int
space(string& str)
{
int
i=0;
while
(!
iscntrl
(str[i]))
{
putchar
(str[i]);
i++;
}
return
0;
}
// Driver Code
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 contribute.geeksforgeeks.org or mail your article to contribute@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.
Please Login to comment...