https://rentry.org/PPP2_p397

// Code derived from Stroustrup's PPP2 book
// § 11.6 Character classification
//  -and beginning on p 397

#include <cctype>
#include <iostream>

using namespace std;

int main()
{
  // example input:  1 + 4 * x <= y / z * 5
  cout << "\n>  ";

  // exposition only:
  // note: this is an infinite loop; you'll need to break out of it yourself
  // -(ie, use ctrl+d to end input; see input stream comments on p 124)
  for (char ch; cin.get(ch);) {
    if (isspace(ch)) {  // if ch is whitespace
      ;                 // nop; do nothing (i.e., skip whitespace)
    }

    if (isdigit(ch)) {
      // read a number
    } else if (isalpha(ch)) {
      // read an identifier
    } else {
      // deal with operators
    }
  }
}

// exposition only:
void test(char c)
{
  isspace(c);   // is c whitespace? (' ', '\t', '\n', etc.)
  isalpha(c);   // is c a letter? ('a'..'z', 'A'..'Z') note: not '_'
  isdigit(c);   // is c a decimal digit? ('0'..'9')
  isxdigit(c);  // is c hexadecimal digit: decimal digit or 'a'..'f' or 'A'..'F'
  isupper(c);   // is c an upper-case letter?
  islower(c);   // is c a lower-case letter?
  isalnum(c);   // is c a letter or a decimal digit?
  iscntrl(c);   // is c a control character (ACSII 0..31 and 127)
  ispunct(c);   // is c not a letter, digit, whitespace, or invisible control
                // character
  isprint(c);   // is c printable (ASCIII ' '..'~')
  isgraph(c);   // is c isalpha()|isdigit()|ispunct() (note, not space)

  toupper(c);  // c or c's upper case equivalent
  tolower(c);  // c or c's lower case equivalent
}

// put s into lower case
void tolower(string& s)
{
  for (int i = 0; i < (int)s.length(); ++i)
    s[i] = tolower(s[i]);
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_11/main_p397.cpp && ./a.out

PrevUpNext

Edit
Pub: 09 Apr 2023 06:04 UTC
Edit: 03 May 2023 10:35 UTC
Views: 566