循环,if语句,使用inputFile的函数仅输出0

时间:2012-11-15 09:59:16

标签: c++ loops if-statement inputstream validation

我需要一些认真的帮助才能让它运行起来。我想我正在使用inputFile弄乱循环..程序编译并且.txt文件位于正确的目录中。 txt是一个替换用户输入的测试文件。该文件在三个单独的行中包含三个数字:1,115和10。 这是我的代码:

//Headers
//Headers
#include<iostream>
#include<fstream>
#include<cmath>
#include<cstdlib>
#include<iomanip>
using
namespace std;
void PaintJobEstimator(double gallonprice, double wallspace)
{
    double numBucket;
    double hours;
    double bucketCost;
    double laborCharges;
    double totalCost;
    {
    //calculates number of buckets of paint (gallons) needed
    numBucket=1/115*wallspace;
    //calculates paint cost
    bucketCost=gallonprice*numBucket;
    //calculates labor hour
    hours=8/115*wallspace;
    //calculates labor charges
    laborCharges=hours*18;
    //calculates total cost
    totalCost=bucketCost+laborCharges;
    //Console output
    {
        cout << "The number of Gallons of paint required:\t" << numBucket << endl;
        cout << "The hours of labor required:\t" << hours << " hrs" << endl;
        cout << "The labor charges:\t$" << laborCharges << endl;
        cout << "The cost of the paint:\t$" << bucketCost << endl;
        cout << "The total cost of the paint job:\t$" << totalCost << endl;
    }

    }

}

int main ()
{
    int rooms=0; //number of rooms
    double wallspace=0; //wall space measured in square meters
    double gallonprice=0; //Price per gallon
    cout << "=========================================================\n";
    cout << "___________________Paint Job Estimator___________________\n";
    cout << "_________________________________________________________\n";
    //by Jeff Youngblood
    cout << endl;
    ifstream inputFile;
    //open the file
    inputFile.open("17.txt");
    if (inputFile.is_open())
    {
        if (rooms>=1) //validates rooms
        {
            inputFile >> rooms;
        }
        for (int roomNum=1;roomNum<=rooms;roomNum++)
        {
            if (wallspace>1)//validates and inputs wallspace
            {
                inputFile >> wallspace;
            }
        }
        //end loop
        while (gallonprice>10) //validates price per gallon
        {
            inputFile >> gallonprice;
        }
        PaintJobEstimator(gallonprice,wallspace);
        system ("pause");
    }
    else
        cout <<"Error reading file '17.txt', please check your directory.\n";
}

2 个答案:

答案 0 :(得分:2)

此序列

    double wallspace = 0;
    //...
    if (wallspace>1) //validates and inputs wallspace
    {
        inputFile >> wallspace;
    }

不起作用,因为if语句中的条件始终为false。到达那里时,wallspace的值为零,因此您永远不会尝试输入新值。

gallonprice类似,您从不输入值,因为初始条件为false,因此永远不会输入循环。

答案 1 :(得分:1)

您的所有文件读取都是有条件的,期望值大于零,但由于您init room,wallspace和gallonprice为零,因此永远不会读取该文件。因此,PaintJobEstimator被调用0,0。尝试删除条件并从那里开始工作。