this is only my second time posting here so I hope I am doing this correctly. I need to have the user input a string (usrinput) of any length and make a selection 1 - 4. I have completed 2, 3, and 4, but I cannot figure out how to do selection 1. if the user enters a string "This is a Test" and selects option 1, if odd I need to find the middle letter. if even instead of displaying the middle two letters, I need to let the user know that there is no middle. I feel like I have the function close to being correct, but I'm having a hard time understanding what it means. Any help is greatly appreciated, and I can try to elaborate further if necessary.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string usrinput, upper, lower, str;
int selection, middle, i;
bool menu = true;
cout << "=============================================================" << endl;
cout << "Welcome to my program. Enter a sentence and make a selection: " << endl;
cout << "Enter -999 to exit the program. " << endl;
cout << "=============================================================" << endl;
cout << "1. display middle character. " << endl; //if user selects 1, do "..."
cout << "2. display sentence uppercase " << endl; //if user selects 2, do "..."
cout << "3. display sentence lowercase" << endl; //if user selects 3, do "..."
cout << "4. display sentence backwards" << endl; //if user selects 4, do "..."
cout << "Enter a sentence: " << endl;
getline(cin, usrinput); //sentence input
while (menu == true)
{
cout << "Make a selection: " << endl; // if selection is 1 - 4 || -999 (good input) anything <1 or >5 (bad input, loop until selection = 1 - 4
cin >> selection;
//Step 1. Input Validation
while (selection != 1 && selection != 2 && selection != 3 && selection != 4 && selection != -999) //If the selection is not 1 - 4 || -999 loop until selection is valid.
{
cout << "Invalid Entry. Please make another selection: " << endl;
cin >> selection;
}
if (selection == 1) // if the user enters 1: show middle character if there is one / let the user know there isn't one.
{
cout << "Middle: " << endl;
cout << "=======" << endl;
if (((i = usrinput.length() /2 % 2) == 1))
{
cout << usrinput[i];
cout << endl;
}
else if (((i = usrinput.length() / 2) % 2) >= 1)
{
cout << "There is no middle";
cout << endl;
}
}
CodePudding user response:
For your selection 1 if statement, all you need to do is check if the string evenly divides by 2 to determine if it is even or odd, no need to divide by 2.
You also can just have an else statement right after the if which accounts for even numbers.
if (((i = usrinput.length() % 2) == 1))
{
i = usrinput.length()/2;
cout << usrinput[i];
cout << endl;
}
else
{
cout << "There is no middle";
cout << endl;
}