Capitalizing first letter of every word in a sentence

I know this forum may be encounter this age old problem several times, but I just want to understand how to properly execute the code required to accomplish this task.

Right now, I want to limit the use of my code to the following libraries:
-iostream
-cctype
-string
-iomanip

Also, I would like to avoid creating any user defined functions.

I understand that I will require functions such as toupper[] to convert the letters to uppercase letters, a for loop to evaluate each word of the sentence, and something like a counter to only capitalize the first letter of the word being evaluated.

This is currently what my code looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>

using namespace std;

int main()
{
   char sentence[80];
   char title;

   cout << "Please enter a title." << endl;

   cin.getline(sentence, 80);

   title = toupper(sentence[0]);

   cout << title << endl;
   
   return 0;
}


I understand that by identifying "title" as a char variable, it will only return the first character of the word that's read, despite using getline to read the whole user input.

So far I've been able to build several complex programs, but for some reason I get hung over by the use of strings, so I would appreciate any pointers.
Hi,

Just a hint to begin with

a new word starts with a space before, so find the space and capitalize the next
"...so I would appreciate any pointers. "


PUN INTENDED! I kid.

Anyway, we all get hung up. To add to programmer007:

Don't forget stringstreams exist as well. As much "fun" as .get() and isspace() is (please note the sarcasm) and assuming your library limits are self-imposed and you're open to adding <sstream>, I think you'll find the ability to stream a getline() to extract individual words will drastically simplify your project. After all, .get()ing or iterating your way to an isspace() so you can give your next char to toupper()? It'll work, but...
Just remember that streams will loose whitespace formatting.
closed account (48T7M4Gy)
This is part of the story. Depends whether you want to modify the sentence or create a separate title.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int main()
{
   const int size = 80;
   
   char sentence[size];
   
   std::cout << "Please enter a sentence.\n";
   std::cin.getline(sentence, size); // make sure limit is not excedded

   sentence[0] = toupper(sentence[0]);
   
   for (int i = 1; i < size; i++)
   {
        if ( sentence[i - 1] == ' ' )
            sentence[i] = toupper( sentence[i] );
   }

   std::cout << sentence << std::endl;
   
   return 0;
}
Hope this helps

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
#include <iostream>

using namespace std;

void capitalize(string &str)
{
	bool check;
	check=false;		
	for(int i=0;i<str.length();i++)
	{
		if(check==false && (str.at(i)>='a' && str.at(i)<='z')  )//check if its a new word. 
			str.at(i)=str.at(i)+'A'-'a';
		
		if((str.at(i)>='a' && str.at(i)<='z') || (str.at(i)>='A' && str.at(i)<='Z') )//you can also change this condition to check for a space in the string
			check=true;							//if(str.at(i)!=' ')		
		else 									//true... if character at i is an alphabet and false if not
			check=false;							//it reiterates and changes the case of the next character depending on the condition
	}
}

int main()
{
	string str;
	str="this is a test line";
	capitalize(str);
	cout<<str;
	return 0;
}
Programmer007, I figured that out, thanks to kemort. The next order of business is to lowercase all other letters within a word.

Yawzheek, you were quick to catch that haha!

brown ogum, I am examining and testing out your program.

Thanks y'all for the help. I'll let you know if I figure it out.
closed account (48T7M4Gy)
The next order of business is to lowercase all other letters within a word.

An easy way to do this might be the perhaps inelegant but simple way of first converting all characters in the sentence to lower case and then making a second pass capitalizing the initial letter of each word.
kemort, so I've heard, and it makes sense to do so just to have uniform formatting to begin with.

brown ogum, I like the style of your program. I tried the condition where if(str.at(i) != ' '; I thought I could add in a str.at(i) = str.at(i) + 'a' - 'A'; within this block, thinking it would do the opposite of the equation in the first if statement and make each character before the ' ' and after the first character a lowercase character. I guess that doesn't work lol
closed account (48T7M4Gy)
Check it out , maybe this is the way:
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
#include <iostream>

int main()
{
   const int size = 80;
   
   char sentence[size];
   
   std::cout << "Please enter a sentence.\n";
   std::cin.getline(sentence, size); // make sure limit is not excedded

   sentence[0] = toupper(sentence[0]);
   
   for (int i = 1; i < size; i++)
   {
        if ( sentence[i - 1] == ' ' )
            sentence[i] = toupper( sentence[i] );
        else
            sentence[i] = tolower(sentence[i]);
   }

   std::cout << sentence << std::endl;
   
   return 0;
}


Please enter a sentence.
HERE we arE wITh an ImprOVEMenT.
Here We Are With An Improvement.
 
Last edited on
Well, might as well join in the fun:

1
2
3
4
5
6
7
8
9
10
11
12
#include <locale>

std::string totitle( std::string s, const std::locale& loc = std::locale() )
{
  bool last = true;
  for (char& c : s)
  {
    c = last ? std::toupper( c, loc ) : std::tolower( c, loc );
    last = std::isspace( c, loc );
  }
  return s;
}

Enjoy.
A "state machine" is a logical construct that has discrete "states"; a memory about its past. The machine changes state on "events".

Lets assume that our "machine" has three possible states:
A) Previous character was not part of a word.
B) Previous character was an initial.
C) Previous character was part of a word.

The current character too has three types:
1) isalpha()
2) isspace()
3) other

Now we have nine combinations, which each might require different treatment.
For example A+1 means that we are looking at an initial, so:
- change state to B
- toupper()

On the other hand, C+1 is just a continuation of a word, so state remains C and tolower().

The machine should be in state A before the first character of input.


There are many ways to implement the concept.
kemort, thanks! This is on point, since it's basically one line of code and looks clean. Plus it works how it should! I didn't think it could look so simple. Like I said, understanding strings and chars, even arrays, is not my forte compared to that of scripting for mathematical computations and fundamental output of information.

Duoas, haha might as well right? I like to get a look at different styles of coding. Gives me a wider perception of how to engage a problem, as I don't really look at how my peers script their codes. Thanks for the input!
Topic archived. No new replies allowed.