這只是我第二次在這里發帖,所以我希望我這樣做是正確的。我需要讓用戶輸入任意長度的字串 (usrinput) 并進行選擇 1 - 4。我已經完成了 2、3 和 4,但我不知道如何進行選擇 1。如果用戶輸入字串“這是一個測驗”并選擇選項 1,如果奇怪,我需要找到中間的字母。如果即使不顯示中間的兩個字母,我也需要讓用戶知道沒有中間。我覺得我的功能接近正確,但我很難理解它的含義。非常感謝任何幫助,如有必要,我可以嘗試進一步詳細說明。
#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;
}
}
uj5u.com熱心網友回復:
對于你的選擇 1 if 陳述句,你需要做的就是檢查字串是否被 2 整除以確定它是偶數還是奇數,不需要除以 2。
你也可以在 if 后面加上一個 else 陳述句,它占偶數。
if (((i = usrinput.length() % 2) == 1))
{
i = usrinput.length()/2;
cout << usrinput[i];
cout << endl;
}
else
{
cout << "There is no middle";
cout << endl;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/359727.html
