190k views
3 votes
Suggested Time to Spend: 20 minutes. Note: Turn the spelling checker off (if it is on). If you change your answer box to the full screen mode, the spelling checker will be automatically on Please turn it off again Q4.2: Write a full C++ program that will convert an input string from uppercase to lowercase and vice versa without changing its format. See the following example runs. Important note: Your program should be able to read a string, including white spaces and special characters. Example Run 1 of the program (user's input is in bold) Enter the input string john Output string JOHN Example Run 2 of the program (user's input is in bold). Enter the input string Smith Output string SMITH Example Run 3 of the program (user's input is in bold) Enter the input string JOHN Smith Output string: john SMITH

User Chris Mack
by
7.9k points

1 Answer

6 votes

Answer:

Here is an example C++ program that will convert an input string from uppercase to lowercase and vice versa without changing its format:

#include <iostream>

using namespace std;

int main() {

string str;

getline(cin, str);

for (int i=0; i<str.length(); i++) {

if (islower(str[i]))

str[i] = toupper(str[i]);

else

str[i] = tolower(str[i]);

}

cout << str << endl;

return 0;

}

Step-by-step explanation:

We start by including the iostream library which allows us to read user input and write output to the console.

We declare a string variable str to store the user input.

We use getline to read the entire line of input (including white spaces and special characters) and store it in str.

We use a for loop to iterate through each character in the string.

We use islower to check if the current character is a lowercase letter.

If the current character is a lowercase letter, we use toupper to convert it to uppercase.

If the current character is not a lowercase letter (i.e. it is already uppercase or not a letter at all), we use tolower to convert it to lowercase.

We output the resulting string to the console using cout.

We return 0 to indicate that the program has executed successfully.

When the user enters the input string, the program converts it to either uppercase or lowercase depending on the original case of each letter. The resulting string is then printed to the console.

Step-by-step explanation:

User Altabq
by
7.4k points