Problem with array of string from uppercase to lowercase

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.

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
29
30
31
32
// asg7a.cpp
// Written by 
// Fall 2010
// Purpose: Proper Words

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    int i=0;

    const int 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?
A c-string (a string in an array) is terminated by a character value of zero. Hence,

char greeting[] = "Hello world!"

is the same as

char greeting[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };

So your while loop is essentially continuing while the character at i is not the zero character (or "null character").

Hope this helps.
That does make sense, however, if the loop is continuing while the character at i is not zero...wouldn't that be while (!greeting[i])
No, a while loop only continues while the expression in parentheses evaluates to true.
Note that while(str[i]) is the same as while(str[i] != 0)
Topic archived. No new replies allowed.