如何使用循环清理此代码?

时间:2017-10-15 18:11:24

标签: c++ loops visual-c++

基本上,该程序允许用户输入一个句子,并根据用户选择,它将显示句子的中间字符,显示大写或小写,或向后。简单的程序,但我是编程新手,这可能是问题所在。我想弄清楚如何使用循环而不是大量的if语句。当我尝试创建一些循环时,它会破坏代码的某些部分,但我确信这是因为我没有正确理解它们。如果您对代码有任何批评或任何建议,我会很高兴听到它。提前谢谢!

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;


int main()
{
int sel;
string sent;
bool validinput;
int i;
int x;
int j;
int a;

cout << "Welcome to my program. Enter a sentence and select one of the options below.\n";
cout << "Enter -999 to exit the program." << endl;
cout << "============================================================================" << endl;
cout << endl;
cout << "1. Display the middle character if there is one." << endl;
cout << "2. Convert to uppercase." << endl;
cout << "3. Convert to lowercase." << endl;
cout << "4. Display backwards." << endl;
cout << "Enter a sentence: ";
    getline (cin, sent);
cout << "Selection: ";
    cin >> sel;

    if (sel < 1 && sel > 4)
    {
        cout << "Invalid input. Try again. Selection: ";
        cin >> sel;
        validinput = false;
    }
    else (sel >= 1 && sel <= 4);
    {
        validinput = true;
    }

    if (validinput == true)
    {
        if (sel == 1)
        {
            j = sent.length() / 2;
            cout << "The middle character is: " << sent.at(j) << endl;
        }

        if (sel == 2)
        {
            for (int i = 0; i < sent.length(); i++)
            {
                if (sent.at(i) >= 'a' && sent.at(i) <= 'z')
                {
                    sent.at(i) = sent.at(i) - 'a' + 'A';
                }
            }
            cout << "Uppercase: " << sent << endl;
        }

        if (sel == 3)
        {
            for (int x = 0; x < sent.length(); x++)
            {
                if (sent.at(x) >= 'A' && sent.at(x) <= 'Z')
                {
                    sent.at(x) = sent.at(x) - 'A' + 'a';
                }
            }
            cout << "Lowercase: " << sent << endl;
        }

        if (sel == 4)
        {
            for (a = sent.length() - 1; a >= 0; a--)
            {
                cout << sent.at(a);
            }
        }
    }

system("pause");
return 0;

}

2 个答案:

答案 0 :(得分:1)

我个人会使用switch选择语句。我粗略地这样做只是为了解释它如何使你的代码更友好和可理解。

int sel;
bool validInput = false;

    switch(sel)
    {
        case 1:
            //display middle char if there's one
        case 2:
            //convert to uppercase
        case 3:
            //convert to lowercase
        case 4:
            //display backwards
            validInput = true;
            break;
        default: //if number does not meat 1, 2, 3 or 4
            validInput = false;
            break;
    }

正如您可能注意到的那样,对于案例1,案例2,案例3和案例4,如果数字介于1到4之间,则会有一个中断; validInput为true。

参考:Switch Selection Statement

答案 1 :(得分:0)

我建议使用switch。它会更好地组织您的代码。从查看代码开始,您似乎明智地使用了forif。但我建议检查输入的if语句替换为switch