If Then Else running Then no matter what

When I run this it executes the Then portion even if it doesn't meet the parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
  string word;
  char firstLetter;
  string pigLatin;
int main()
{
  string word;
  char firstLetter;
  string pigLatin;

  cout << "Enter a word! ";
  cin >> word;

  word[0] = tolower(word[0]);
  firstLetter = word[0];
  if (firstLetter == 'a' || 'e' || 'i' || 'o' || 'u') {
  pigLatin = word + "ay";
  pigLatin[0] = toupper(pigLatin[0]);
  } else {
  word = word.erase(0,1);
  pigLatin = word + firstLetter + "ay";
  pigLatin[0] = toupper(pigLatin[0]);
  }

  cout << "This is your word in pig-latin! ";
  cout << firstLetter;

  return 0;
}

So Tomato becomes Tomatoay instead of Omatotay
When I comment out the If Then and the vowel parts it works (except then it doesn't do vowels properly)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
  string word;
  char firstLetter;
  string pigLatin;
int main()
{
  string word;
  char firstLetter;
  string pigLatin;

  cout << "Enter a word! ";
  cin >> word;

  word[0] = tolower(word[0]);
  firstLetter = word[0];
  //if (firstLetter == 'a' || 'e' || 'i' || 'o' || 'u') {
  //pigLatin = word + "ay";
  //pigLatin[0] = toupper(pigLatin[0]);
  //} else {
  word = word.erase(0,1);
  pigLatin = word + firstLetter + "ay";
  pigLatin[0] = toupper(pigLatin[0]);
  //}

  cout << "This is your word in pig-latin! ";
  cout << pigLatin;

  return 0;
}
if (firstLetter == 'a' || 'e' || 'i' || 'o' || 'u')
Is equivalent to
if ((firstLetter == 'a') || ('e') || ('i') || ('o') || ('u'))
Where you mean
if (firstLetter == 'a' || firstLetter == 'e' || firstLetter == 'i' || firstLetter == 'o' || firstLetter == 'u')
Last edited on
Thanks for the help! That fixed it. But why'd it always do the Then? Why not ignore the rest after 'a' and go to the Else?
Why not ignore the rest after 'a' and go to the Else?

Because if the condition (firstLetter == a) evaluates to false, the term on the other side of the OR operator has to be checked to see if it is true.

Consequentially, the value 'e' is true. In fact, every character except the NUL byte '\0' is true in a boolean context. Since 'e' is true, no other conditions are checked, per the short-circuiting rules, and the true-statement is executed.
Last edited on
Topic archived. No new replies allowed.