2017-10-18 83 views
-2

在我正在創建的程序中搜索潛在錯誤時,我得到了 「[錯誤] 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維度;並在循環之前初始化它 –

回答

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

@quetzalcoatl在你的命令:P – user463035818

+0

YAY,謝謝:) – quetzalcoatl

+0

對不起,這不是我正在尋找。 –

相關問題