检查数字输入,如果未找到数字,则默认为值

时间:2015-10-25 20:44:37

标签: c++ loops math

我试图在我的程序中插入一个语句,检查文本文件中的值是否为数值。如果值是一个字符(字符串),那么它使变量等于0.基本上我希望我的代码使所有不是数字的值默认为0。

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <math.h>
#include <iomanip>
#include <sstream>
#define M_PI 3.14159265358979323846 //pi
using namespace std;

int main()
{
    double RecWidth, RecHeight, CirRadius, sumRadius, sumCircArea,sumCircumference,sumWidth, sumHeight, sumRecArea, sumPerimeter;
    int Age, Savings, sumAge, sumPeople,sumSavings;
    string FirstName, LastName;

    sumWidth = 0;
    sumHeight = 0;
    sumRecArea = 0;
    sumPerimeter = 0;
    sumRadius = 0;
    sumCircArea = 0;
    sumCircumference = 0;
    sumAge = 0;
    sumPeople = 0;
    sumSavings = 0;

    ifstream FileInput;
    ofstream FileOutput;

    FileOutput << fixed << showpoint << setprecision(2);

    FileInput.open("inData_Normal.txt");
    FileOutput.open("outputFile.txt");

    if (!FileInput.is_open())
    {
        return 1;
    }

    while (FileInput >> RecHeight >> RecWidth >> CirRadius >> FirstName >> LastName >> Age >> Savings)
    {
        sumHeight = sumHeight + RecHeight;
        sumWidth = sumWidth + RecWidth;
        sumRecArea = sumRecArea + (RecHeight * RecWidth);
        sumPerimeter = sumPerimeter + (2 * (RecHeight + RecWidth));
        sumRadius = sumRadius + CirRadius;
        sumCircArea = sumCircArea + (M_PI * CirRadius * CirRadius);
        sumCircumference = sumCircumference + (2 * M_PI * CirRadius);
        sumAge = sumAge + Age;
        sumSavings = sumSavings + Savings;
        sumPeople = sumPeople + 1;
    }

    FileOutput << "Rectangle:" << "\n";
    FileOutput << "The total Lengths = " << sumHeight << ", width = " << sumWidth <<", area = "<< sumRecArea << "," << "\n";
    FileOutput << "Perimeter = " << sumPerimeter << "\n" << "\n";
    FileOutput << "Circle:" << "\n";
    FileOutput << "The total Radius = "<< sumRadius << ", area = "<< sumCircArea <<", circumference = "<< sumCircumference << "\n"<< "\n";
    FileOutput << "Person:"<< "\n";
    FileOutput << "Total number of persons = " << sumPeople << "\n";
    FileOutput << "Total Age = "<< sumAge <<"\n";
    FileOutput << "The Total savings = "<< sumSavings;

    FileInput.close();
    FileOutput.close();
    return 0;
} 

2 个答案:

答案 0 :(得分:1)

将您的RecHeightRecWidth,...定义为std::string。然后,在while循环中,您必须插入:

sumHeight = sumHeight + std::atof(RecHeight.c_str());
sumWidth = sumWidth + std::atof(RecWidth.c_str());

等等。 std::atof位于<cstdlib>库中。如果是,则返回0.0 字符串的内容无法转换为double。否则,它将相应的值返回为double

答案 1 :(得分:1)

如果您正在寻找快速黑客,可以按如下方式更改while语句:

while (FileInput >> RecHeight)
{
    FileInput >> RecWidth >> CirRadius >> FirstName >> LastName >> Age >> Savings;
...
}

这将允许您在while语句中检查新记录(RecHeight必须是有效的浮点数才能使此代码生效)。然后,对于任何缺失或无效的输入,所有其余值都将默认为0.