Yutat
Yutat

Reputation: 1

How to capitalize first letter of each word if it starts with "a" or "o"?

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.

Upvotes: 0

Views: 45

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

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'

Upvotes: 4

Related Questions