0

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];
       }
       
   }
}
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Look up `std::isupper` (and possibly `std::copy_if`). – Jerry Coffin Mar 19 '22 at 21:26
  • `if ( std::isupper(name[i])) { cout << name[i]; }`. The system knows what uppercase characters are using `std::isupper`. It is not a given that uppercase characters are only `A` through `Z`. For example, accented uppercase characters. – PaulMcKenzie Mar 19 '22 at 21:46
  • Ok, I understand that, I have one question... Does the program when compiled even know what charatchers are uppercase and lowercase when comparing them in if statement like I did? –  Mar 19 '22 at 22:02

1 Answers1

0

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().

  • 1
    The first part of your answer is incorrect. It compares against name[I] first. Though, realistically, the optimizer would probably optimize out the if statement entirely, because it's always true. – ChrisMM Mar 19 '22 at 21:39
  • @ChrisMM oops didn't notice that, edited. and yeah there's optimizer.... – AC0xRPFS001 Mar 19 '22 at 21:46
  • @AC0xRPFS001 *Alternatively you can do name[i] >= 'A' || name[i] <= 'Z'* -- That will not work on a system that isn't ASCII and may have a different collating sequence (like EBCDIC). Showing code like that to see if a character is uppercase is bad code. Using `std::isupper` is the only real solution to properly determine uppercase. – PaulMcKenzie Mar 20 '22 at 20:45
  • @PaulMcKenzie aight i see, thanks for reminding. I just removed that part. – AC0xRPFS001 Mar 21 '22 at 06:51