【发布时间】:2021-12-28 02:42:08
【问题描述】:
这只是我第二次在这里发帖,所以我希望我这样做是正确的。 我需要让用户输入任意长度的字符串 (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;
}
}
【问题讨论】:
-
算法应该是“如果长度为奇数 [length % 2 == 1] 则输出字符串[length / 2]”。如果您不理解,请在一张纸上浏览代码。
标签: c++ string function loops if-statement