c++ - How do I do this with switch instead of if esle? -


i taking first programming course , assignment redo previous program (this one) using switch statement. thought switch used compare single characters.

the program receives string , counts numbers, letters, other characters, , total characters.....

#include <iostream>  using namespace std;  int main() {     char s[50];     int i;     int total = 0;     int letters = 0;     int numbers = 0;     int others = 0;          cout << "enter continuous string of characters no blank spaces" << endl;     cout << "(example: abc1234!@#$%)" << endl << endl;     cout << "enter string: ";     cin >> s;     cout << endl;      = 0;     while (s[i] != 0)     {         if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'a' && s[i] <= 'z'))             letters++;         else if ((s[i] >= '0' && s[i] <= '9'))             numbers++;         else             others++;         i++;         total++;     }      cout << letters << " letters" << endl;     cout << numbers << " numbers" << endl;     cout << others << " other characters" << endl;       return 0; } 

with particular situation if/else best way (as said @zenith) if wished switch statements do

switch(s[i]) {     case `0`:     case '1':     case '2':     //repeat '3'-'8'     case '9':         //do whatever want when digit here         break;     case 'a':     case 'a':     case 'b':     case 'b':     //repeat 'c'-'y'     case 'z':     case 'z':         //do whatever want when letter         break;     default:         //do whatever want when not letter or digit         break; } 

when case matches in switch statement, corresponding break executed - that's how can group cases this


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -