D. B. D. B. - 2 months ago 10
C++ Question

How do I check if a word starts with a capitalized letter, and place a condition if so?

I am trying to do a program that "reads in a line of text the user inputted and replaces all four-letter words with the word 'baby', and if that four-letter word's first letter is capitalized (e.g. Love), it must be replaced with the word 'Baby'. The program must continue unless the user enters 'exit'."

I already accomplished the part where the program is supposed to replace all four-letter words with the word "baby", and the program should only terminate if the user enters "exit", but I can't seem to figure out how can I check if the word starts with a capitalized letter and if so, replace it with the word "Baby" instead.

Here is my program:

#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
#include <cctype>
using namespace std;

int main()
std::string input;
std::string word;
while (std::cin >> input)
if (input == "exit")

std::stringstream ss(input);
int count = 0;

while (ss >> word)

if(word.size() == 4)
word = "baby";

std::cout << word << ' ';




To be more clear:

If I enter
You are my love
, it outputs
You are my baby
, correct.

But if I enter
You are my Love
, it should output
You are my Baby
, but I can't seem to figure out how. Thanks for the help.


The problem reduces to inspecting the first letter of word: you can use word[0] to do that, having checked that word has a non-zero length.

What you can't do is use if (word[0] >= 'A' || word[0] <= 'Z') since that makes assumptions about the encoding used by your plaform. (EBCDIC for example does not have the upper case letters in one block!)

What you can do is make use of std::isupper, and allow it to use its default locale. See http://en.cppreference.com/w/cpp/string/byte/isupper.

Putting this together, use if (!word.empty() && std::isupper(word[0])), nothing that due to the short-circuitting nature of &&, the right hand argument is only evaluated if word is not empty.