有没有更好的方法来格式化这个while循环?

时间:2017-10-18 19:42:40

标签: c++ arrays string file while-loop

在我正在创建的程序中搜索潜在错误时,我得到了   " [错误] ISO C ++禁止指针和整数[-fpermissive]之间的比较。"

错误来自我的while循环,其中我打算程序只接受来自用户的以下输入。现在,我正在考虑为这个使用数组。

我该如何解决这个问题?如果任何人有任何更多的细节,我很乐意通过展示我是什么来提供他们(最近)。

int main () // While using one of the three functions to make conversions, 
// the program will create the table based on following information. 
{
    char dimension;
    double u1, u2;  
    int starting_value, ending_value, increment, startingUnitDigits, 
    endingUnitDigits;
    cout << "-------------------------------------------------------------------------------------------------";
    cout << "Please answer the following questions as they appear.";
    cout << "Check spelling, use correct abbreviation for units of measurement, and avoid negative values.";
    cout << "-------------------------------------------------------------------------------------------------";
    cout << "Enter the dimensions from the following choices: length, mass and time. (i.e.: 'length,' 'Length').";
    while (!(dimension == "length" || dimension == "Length" || dimension == "mass" || dimension == "Mass" || dimension == "time" || dimension == "Time"))
    {
        cout << "----------------------------------------------------------------------------------------------------";
        cout << "Error! Input for Dimension, " << dimension << ", was either an invalid choice or typed incorrectly.";
        cout << "Please know that this programs accepts length, mass, and time only!";  
        cout << "----------------------------------------------------------------------------------------------------";
        cout << "Enter the dimensions from the following choices: length, mass and time. (i.e.: 'length,' 'Length').";
        cin >> dimension;   

1 个答案:

答案 0 :(得分:1)

评论已经非常详尽,所以我只想总结一下:

dimension是单个char,您无法与字符串文字进行比较,因此会出错。您应该使用std::string代替。

一旦你改变了,问题仍然是你在从cin读取任何内容之前检查用户输入。你应该反过来做。

如果您使用容器并尝试在该容器中查找用户输入,则您的条件将更具可读性。

所以它会是这样的:

std::vector<std::string> correct_input{"Foo","foo","f00"};
while(true) {
    std::string dimension;
    std::cin >> dimension;
    auto it = std::find(correct_input.begin(),correct_input.end(),dimension);
    if (std::cin.fail() || it==correct_input.end()) {
        // print error and continue to ask for input
        std::cin.clear();  // clear possible error flags
    } else {
       // do something with input
       break;
    }
}