Uppercase and Lowercase HELP

May 27, 2016 at 7:19pm
Hello everyone,
I am stuck with this problem. The problem is ask user to enter a string, then convert the odd words all to uppercase, the even words are lower case. Below is my program, and I still get all of them in uppercase. Please help. Appreciate that.

#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
int main()
{
bool up = false;
char s[100];
cout << "Please enter a string: ";
cin.getline(s, 100);
for (int i = 0; i < strlen(s); i++)
{
if (up = true)
{
s[i] = toupper(s[i]);
}
else if (s[i] == ' ')
{
up = !up;
}
else
{
s[i] = tolower(s[i]);
}
}
cout << s << endl;
system("pause");
return 0;
}

May 27, 2016 at 7:21pm
for example:
input: Hel lo i am liz
output: HEL lo I am LIZ
May 27, 2016 at 7:23pm
if (up = true) = is the assignment operator.


Put either
if (up == true)
or simply
if (up)
May 27, 2016 at 7:34pm
Thank you s much Chervil, it works now for the first two words, the rest are all in lowercase. D you have suggestion for "else if (s[i] == ' ')"?
May 27, 2016 at 8:02pm
The test for a space is sandwiched in the middle of an if-else chain, meaning it only gets executed some of the time. Move it to the start (still inside the for-loop) so it will detect every space.
May 27, 2016 at 8:15pm
Awesome. Thank a lot Chervil!!!
May 27, 2016 at 8:54pm
Here is a basic outline of how I would do this.

I would use 2 variables: string String and int word
First I would ask for input:
1
2
cout << "Please enter a string: ";
getline(cin, String);


Then I would start the for loop, setting the limit at String.size() instead of strlen(s). The first conditional would be used to increment the word count if there is a space found. The second conditional checks if code is currently looking at an odd number word. The third conditional would see if the code is looking at an even word.

Inside the second conditional you need a method to make all the letters uppercase. Add a conditional inside to check for lowercase letters. Inside that conditional add a line that changes uppercase to lowercase letters.

Inside the third conditional you need a method to make all the letters lowercase. Add a conditional inside to check for uppercase letters. Inside that conditional add a line that changes lowercase to uppercase letters.

If you don't know how to change cases, look at the ascii table. A = 65, Z = 90, a = 97, z = 122.
Last edited on May 27, 2016 at 8:54pm
May 27, 2016 at 10:45pm
If using a standard string s, all you would need is this:
1
2
3
4
5
6
    bool up = true;
    for (char & c : s)
    {
        if (c == ' ') up = !up; 
        c = up ? toupper(c) : tolower(c);
    }

... though if there are multiple spaces or other whitespace that wouldn't work.
Last edited on May 27, 2016 at 10:47pm
May 27, 2016 at 11:36pm
Great. thank you guys.
Topic archived. No new replies allowed.