有没有更好的方法来解决这个问题?

时间:2017-02-24 22:58:46

标签: c++

我基本上试图制作一个将罗马数字变成十进制的程序,这是为了验证只接受罗马数字作为输入。

我确信有更有效的方法可以做到这一点。我对编程非常陌生。

int main() 
{
    string valid = {"IIIIIVIIXIILIICIIDIIMIVIIVVIVXIVLIVCIVDIVMIXIIXVIXXIXLIXCIXDIXMILIILVILXILLILCILDILMICIICVICXICLICCICDICMIDIIDVIDXIDLIDCIDDIDMIMIIMVIMXIMLIMCIMDIMMVIIVIVVIXVILVICVIDVIMVVIVVVVVXVVLVVCVVDVVMVXIVXVVXXVXLVXCVXDVXMVLIVLVVLXVLLVLCVLDVLMVCIVCVVCXVCLVCCVCDVCMVDIVDVVDXVDLVDCVDDVDMVMIVMVVMXVMLVMCVMDVMMXIIXIVXIXXILXICXIDXIMXVIXVVXVXXVLXVCXVDXVMXXIXXVXXXXXLXXCXXDXXMXLIXLVXLXXLLXLCXLDXLMXCIXCVXCXXCLXCCXCDXCMXDIXDVXDXXDLXDCXDDXDMXMIXMVXMXXMLXMCXMDXMMLIILIVLIXLILLICLIDLIMLVILVVLVXLVLLVCLVDLVMLXILXVLXXLXLLXCLXDLXMLLILLVLLXLLLLLCLLDLLMLCILCVLCXLCLLCCLCDLCMLDILDVLDXLDLLDCLDDLDMLMILMVLMXLMLLMCLMDLMMCIICIVCIXCILCICCIDCIMCVICVVCVXCVLCVCCVDCVMCXICXVCXXCXLCXCCXDCXMCLICLVCLXCLLCLCCLDCLMCCICCVCCXCCLCCCCCDCCMCDICDVCDXCDLCDCCDDCDMCMICMVCMXCMLCMCCMDCMMDIIDIVDIXDILDICDIDDIMDVIDVVDVXDVLDVCDVDDVMDXIDXVDXXDXLDXCDXDDXMDLIDLVDLXDLLDLCDLDDLMDCIDCVDCXDCLDCCDCDDCMDDIDDVDDXDDLDDCDDDDDMDMIDMVDMXDMLDMCDMDDMMMIIMIVMIXMILMICMIDMIMMVIMVVMVXMVLMVCMVDMVMMXIMXVMXXMXLMXCMXDMXMMLIMLVMLXMLLMLCMLDMLMMCIMCVMCXMCLMCCMCDMCMMDIMDVMDXMDLMDCMDDMDMMMIMMVMMXMMLMMCMMDMMM"};

    string s;
    while (true) {
        cout << "Please enter a roman numeral or Q to quit the program: ";
        cin >> s;

        if (valid.find(s) != string::npos) {
            int num;
            num = intConversion(s);
            cout << num << "\n";
        }
        else if (s == "Q") {
            cout << "Thank you for using the program." << "\n";
            break;
        } else {
            cout << "Invalid letter!" << "\n";
        }
    }
    return 0;
    system("pause");
}

2 个答案:

答案 0 :(得分:1)

那个valid字符串非常丑陋且不必要的开销。我建议完全摆脱它,如果输入无法转换,只需让intConversion()返回错误。

bool intConversion(const string &s, int *num)
{
    // parse s and set *num as needed...
    return true or false accordingly;
}

int main()
{
    string s;
    while (true) {
        cout << "Please enter a roman numeral or Q to quit the program: ";
        cin >> s;
        if (s == "Q") {
            cout << "Thank you for using the program." << "\n";
            break;
        }

        int num;
        if (intConversion(s, &num))
            cout << num << "\n";
        } else {
            cout << "Invalid input!" << "\n";
        }
    }

    system("pause");
    return 0;
}

答案 1 :(得分:0)

我找到了解决方案。

int main() 
{
string valid = {"IVXLCDM"};

string s;
while (true) {
    cout << "Please enter a roman numeral or Q to quit the program: ";
    cin >> s;

    if (valid.find_last_of(s) != string::npos) {
        int num;
        num = intConversion(s);
        cout << num << "\n";
    }
    else if (s == "Q") {
        cout << "Thank you for using the program." << "\n";
        break;
    } else {
        cout << "Invalid letter!" << "\n";
    }
}
return 0;
system("pause");

}