2013-07-04 255 views
0

我正在尝试编写一个程序,该程序从用户处获取测量值并将它们输入到矢量中。 while循环继续,直到用户输入'|'在此时它会跳出循环并打印测量结果。然而,我遇到的问题是,当试图将测量结果添加到矢量中时。我使用了调试器,发现循环从未实际进入for循环,因此无法达到“push_back语句”。While循环内的C++ For循环

该程序是Bjarne Stroustup PPP C++书籍的一部分。

#include "../../std_lib_facilities.h" 

double metreConvert (double userInput , String unit) { 

if (unit == "cm") 
userInput = userInput/100; 
else if (unit == "in") 
userInput = (userInput * 2.54)/100; 
else if (unit == "ft") 
userInput = ((userInput * 12) * 2.54)/100; 
else if (unit == "m") 
userInput; 

return userInput; 
} 

void numbers() { 
double input; 
String unit; 
vector <double> measurements; 

    while (cin >> input >> unit && input != '|'){ 
    if (unit == "cm") 
    input = input/100; 
    else if (unit == "in") 
    input = (input * 2.54)/100; 
    else if (unit == "ft") 
    input = ((input * 12) * 2.54)/100; 
    else if (unit == "m") 
    input; 
     for (int i=0; measurements.size(); i++){ 
      if (i == 0 || input != measurements[i]){ 
      cout << "\nPopping onto vector"; 
      measurements.push_back(input); 
      } 
      else { 
      cout << "\nMeasurment cannot be placed on vector"; 

     } 
     } 
    } 
    cout << "input ended"; 
    } 

void main() { 
cout << "Please enter a number followed by a unit(metres,cm,inches,ft), type '|' when finished inputing:"; 
numbers(); 
} 
+2

请正确缩进你的代码。另外,'for'循环之前的'input'是什么? –

+0

measurements.size() - 也许检查不是0? – Jona

回答

0

雷米说什么,加:

for循环声明的第二部分是一个条件,这应该评估为真或假。在你的情况下,你的情况是measurements.size()

问题是你的测量向量中没有任何东西,所以measurements.size()将返回0.这相当于false。我怀疑这实际上不是你想要做的,你可能是这样意思的:

for (int i=0; i < measurements.size(); i++){ 

即使这样,你的逻辑是错误的。假设您只是试图将每个输入的值添加到测量向量中(如果它不等于之前的测量值),我不明白为什么您需要在这里完成for循环。这将做你想要的:

while (cin >> input >> unit && input != '|') 
{ 
    if (unit == "cm") 
     input = input/100; 
    else if (unit == "in") 
     input = (input * 2.54)/100; 
    else if (unit == "ft") 
     input = ((input * 12) * 2.54)/100; 
    else if (unit == "m") 
     input; //No idea what this is supposed to be - more missing code? 

    if (!measurements.size() || input != measurements[measurements.size()-1]) 
    { 
     cout << "\nPopping onto vector"; 
     measurements.push_back(input); 
    } 
    else 
    { 
     cout << "\nMeasurment cannot be placed on vector"; 
    } 
} 
+0

干杯队友,这是一个很大的帮助 – Shaun1810

3

inputdouble|char。它们不是同一件事。因此cin失败并且您的while循环未输入。要做你正在尝试的,你需要首先输入数据作为string,检查其值为|,如果不匹配,则将其转换为double进行进一步处理。

+0

我知道|是一个字符,我输入到一个double,但我已经得到的代码没有for循环,我添加,所以用户不能两次添加相同的东西。 – Shaun1810

0

此行

for (int i=0; measurements.size(); i++){ 

引起环路如果measurements矢量不为空永远运行(而不是在所有如果向量是空的)。也许你的意思

i < measurements.size()