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;
}
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.
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.