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

问题描述:

在我正在创建的程序中搜索潜在错误时,我得到了 “[错误] ISO C++禁止指针和整数[-fpermissive]之间的比较。”有没有更好的方式来格式化这个while循环?

错误来自我的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; 
+5

'焦炭dimension'其1个字符,并要检查尺寸==“长度” ..等 –

+0

'尺寸==“长度”'比较了' char'带有'const char [7]',因此是错误信息。 – user0042

+2

@Catholic_Ryanite使用std :: string dimension;而不是char维度;并在循环之前初始化它 –

的意见已经相当详尽,所以我只是总结起来:

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; 
    } 
} 
+0

@quetzalcoatl在你的命令:P – user463035818

+0

YAY,谢谢:) – quetzalcoatl

+0

对不起,这不是我正在寻找。 –