[SOLVED] I'm trying to print only uppercase letters from some input using for loop to iterate trough characters, but for some reason it doesn't work

Issue

I’m 100% sure from testing that for loop does iterate through characters how is it suposed to, but the other part of the program isn’t working correctly.
Im trying with if statement to print only uppercase characters.

Here are some input/output samples to get a better pitcure what this program is about:
Input: Tim-Berners-Lee Output: TBL
Input: Albert-Einstein Output: AE

Here is the code:

#include <iostream>
#include <string>
using namespace std;


int main(){
   string name;
   cin >> name;
   int N = name.length();
   
   for (int i = 0; i < N; i++)
   {
       if (name[i] == 'A' || 'B' || 'C' || 'D' || 'E' || 'F' || 'G' || 'H' || 'I' || 'J' || 'K' || 'L' || 'M' || 'N' || 'O' || 'P' || 'Q' || 'R' || 'S' || 'T' || 'U' || 'V' || 'W' || 'X' || 'Y' || 'Z'){
           cout << name[i];
       }
       
   }
}

Solution

Your code will calculate compare name[i] == 'A' first and then take
the result to do OR operation with 'B', 'C', and so on…, which absolutely won’t work.

You should do name[i] == 'A' || name[i] == 'B' || ... or just use std::isupper().

Answered By – AC0xRPFS001

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *