My code is posted below. The code takes the entire string the user inputs and converts everything to uppercase (posted code works with no errors). I am trying to only convert the first letter in each new word to uppercase if it is already not uppercase. If any of the letters are already uppercase then they should be left alone. How do I go about doing that? I'm using Visual Studio 2010. Thanks in advance.
// asg7a.cpp
// Written by
// Fall 2010
// Purpose: Proper Words
#include <iostream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
int i=0;
constint size = 100; // Array size
char str[size]; // Holds the line of user input
cout << "Write a small sentence. " << endl;
cin.getline(str, size);
char c;
while (str[i])
{
c=str[i];
putchar (toupper(c));
i++;
}
system("pause"); // so I can see what is going on
return 0;
}
I suggest you change your lines 25 26 to str[i] = toupper(str[i]);. Then add cout << str; after the loop. That way you will not only print the string but also save the changes should you need it later.
Anyway, as for your problem, you will only need to capitalize the first letter and any letter that goes after a white space. So,
1 2 3 4 5 6 7 8
bool capitalize = true;//so that the firs letter is capitalized
while(str[i]){
if(capitalize) str[i] = toupper(str[i]);
//else do nothing.
if(str[i] == ' ') capitalize = true;//new word!
else capitalize = false;//so that you don't capitalize the rest of the word
i++
}
I got it to work. Thanks!! Quick question though. What is this statement
while (str[i])
actually doing? Variable i is set to zero. I understand loops, but this kind of doesn't make sense...I see it as while str[0] do the following, but wont it only be str[0] on the first character?