0

I have the following c++ code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
void main()
{
    
     ifstream file;

     file.open("file.txt", fstream::out);

     string text;


    while (!file.eof()) {

         getline(file, text);
 
     }

    file.close();





    for (int i = 0; i < 30; i++) {

         if (text[i] == ' ' && text[i + 1] == 'a' || "o") {

             text[i + 1] = toupper(text[i + 1]);
         }
     }

Text of the file:

Cats odds abses intro obsession jam

And I need co capitalize the first letter of words that begin with "a" or "o",but it capitalizes each letter.

Does somebody know how to fix this?

Will be thankful for any answer.

Yutat
  • 1

1 Answers1

4

The problem is this condition:

text[i + 1] == 'a' || "o"

There are two errors here.

  1. The first is that you use a string for "o" not a single character. Use 'o' instead.

  2. The second problem is that the condition is actually the same as

    (text[i + 1] == 'a') || "o"
    

    Which means you compare only text[i + 1] to the character 'a'. So the condition is true if either text[i + 1] == 'a' is true, or if "o" is true. And "o" will always be true, making the whole condition true, always.

The two problems are unrelated. Even if you solve the first one, the second will still remain, as 'o' is also always true.

To solve the second problem you need to compare text[i + 1] with both characters explicitly:

text[i + 1] == 'a' || text[i + 1] == 'o'
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550