2012-12-03 108 views
0

這可能是一個非常快速的解決方法,但我無法弄清楚爲什麼會出現錯誤。'operator'不匹配

代碼:

#include <iostream> 
#include <queue> 
#include <vector> 
#include <iomanip> 
#include <stdlib.h> 
#include <time.h> 

using namespace std; 

int main(int argc, char *argv[]){ 

    srand (time(NULL)); 
    double randomNumber = (double)(rand() % 100)/100; 

    string numCars; 

    cout << "\nPlease enter the number of cars going through the intersection:" << endl; 
    cout << "->"; 
    getline (cin, numCars); 

    for(double i=0; i<numCars; i++){ 
     cout << randomNumber << endl; 
    } 

} 

的錯誤是:

traffic.cpp:80: error: no match for ‘operator<’ in ‘i < numCars’ 
+0

你不能比較字符串和整數。你必須轉換一個。我假設你正在對輸入做一些檢查,這就是爲什麼它是一個字符串,但如果你不是,只需從一個int開始。 – chris

回答

4

numCars是一個字符串。它應該有整數類型(char,short,int,long)

+1

哇。我是個白癡。謝謝! –

+1

只是一個增加的細節:變量我應該很可能是一個int。 –

0

你不能比較字符串與整數,或者你必須爲此定義運算符。 numCars應該是整數嗎?

2

您無法將string與數值進行比較。將用戶輸入讀入unsigned int。你的代碼更改爲:

unsigned int numCars; 
if(!(cin >> numCars)) { 
    // invalid user input, handle it 
} 

for(unsigned int i = 0 ; i < numCars; ++i) { 
    // ... 
} 

我也改變了i數據類型從doubleunsigned int。沒有理由使用浮點數,除非某個小數的汽車可以通過該交點。