Check for space in C++

Use std::isspace(int ch) to check whether given character is a space.

std::isspace(int ch) returns true (that is a non-zero number) if character is any of the following.
  • space (0x20, ' ') 
  • form feed (0x0c, '\f') 
  • line feed (0x0a, '\n') 
  • carriage return (0x0d, '\r') 
  • horizontal tab (0x09, '\t') 
  • vertical tab (0x0b, '\v') 
Header to include <cctype>

Sample code

#include <iostream>
#include <string>
#include <cctype>
void check_isspace(char ch, std::string desc)
{
    if(std::isspace(ch))
        std::cout << desc << " is a space" << std::endl;
    else
        std::cout << desc << " is not a space" << std::endl;
}

int main()
{
    // passing characters
    check_isspace(' ', "space"); // space
    check_isspace('\t', "tab"); // tab
    check_isspace('\v', "vertical tab"); // vertical tab
    check_isspace('\n', "new line"); // new line
    check_isspace('\r', "carriage return"); // carriage return
    check_isspace('\f', "form feed"); // form feed
   
    std::cout << std::endl << "Try again with number represetations instead of char" << std::endl << std::endl;
   
    // passing int values in place of chars
    check_isspace(0x20, "space"); // space
    check_isspace(0x09, "tab"); // tab
    check_isspace(0x0b, "vertical tab"); // vertical tab
    check_isspace(0x0a, "new line"); // new line
    check_isspace(0x0d, "carriage return"); // carriage return
    check_isspace(0x0c, "form feed"); // form feed
   
    std::cout << std::endl << "Try non-space chars" << std::endl << std::endl;
   
    // check few numbers
    check_isspace(5, "number"); // number
    check_isspace(55.99, "decimal number"); // decimal number
   
    // check few non-space chars
    check_isspace('a', "char a"); // char 1
    check_isspace(0x01, "ascii char 01"); // ascii char 1
   
    std::cout << std::endl << "IMPORTANT: floating value is considered as space. Reason: 11.99 becomes 11 when assigned to char parameter, which is line feed(\n)." << std::endl << std::endl;
    check_isspace(11.99, "decimal number"); // IMPORTANT! decimal number
   
    return 0;
}


/*********** Output **********
space is a space
tab is a space
vertical tab is a space
new line is a space
carriage return is a space
form feed is a space
Try again with number represetations instead of char
space is a space
tab is a space
vertical tab is a space
new line is a space
carriage return is a space
form feed is a space
Try non-space chars
number is not a space
decimal number is not a space
char a is not a space
ascii char 01 is not a space
IMPORTANT: floating value is considered as space. Reason: 11.99 becomes 11 when assigned to char parameter, which is line feed(
).
decimal number is a space
*/

No comments:

Post a Comment