C ++ For While循环中的循环

时间:2013-07-04 17:28:54

标签: c++ for-loop while-loop

我正在尝试编写一个程序,该程序从用户那里获取测量值并将它们输入到矢量中。 while循环继续,直到用户输入'|'在这一点上,它突破了循环并打印测量结果。然而,我遇到的问题是在尝试将测量值添加到矢量时。我使用了调试器,发现循环从未真正进入for循环,因此无法访问“push_back语句”。

该计划是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();
 }

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

这一行

for (int i=0; measurements.size(); i++){
如果measurements向量不为空(如果向量为空则完全没有),

会导致循环永远运行。也许你的意思是

i < measurements.size()

答案 2 :(得分:0)

雷米说的话,加上:

for循环声明的第二部分是一个条件,它应该计算为true或false。在您的情况下,您的条件为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";
    }
}
相关问题