2012-12-03 109 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。没有理由使用浮点数,除非某个小数的汽车可以通过该交点。