c++文件提取检查是否为int

c++ infile extraction checking if int

本文关键字:int 是否 检查 文件 提取 c++      更新时间:2023-10-16

我对c++相当陌生,不知道从哪里开始,或者如果它甚至可能,但我想检查一下,看看长度,宽度,半径等实际上是双精度的,如果它们不返回0。

int main() {
ifstream inFile;
ofstream outFile;
string in;
double length, width, tLength = 0, tWidth = 0, areaRec, tAreaRec = 0, parameter, tParameter = 0; 
double radius, tRadius = 0, areaCirc, tAreaCirc = 0, circumference, tCircumference = 0;
double  savings, tSavings = 0; 
int people = 0, age, tAge = 0;
string name1, name2;
inFile.open("inData_with_error.txt");
outFile.open("outData_Normal.txt");
outFile << fixed << showpoint << setprecision(2);
if (!inFile) {
    cout << "ERROR: Unable to open file!" << endl;
    inFile.close();
}
else {
    cout << "Caculating..." << endl;
    while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) {
        cout << length << ", " << width << ", " << radius << ", " << name1 << ", " << name2 << ", " << age << ", " << savings << endl;
        tLength = tLength + length;
        tWidth = tWidth + width;
        parameter = length * 2 + width * 2;
        areaRec = length * width;
        tParameter = tParameter + parameter;
        tAreaRec = tAreaRec + areaRec;
        tRadius = tRadius + radius;
        areaCirc = pow(radius, 2) * PI;
        circumference = (radius * 2) * PI;
        tAreaCirc = tAreaCirc + areaCirc;
        tCircumference = tCircumference + circumference;
        people = people + 1;
        tAge = tAge + age;
        tSavings = tSavings + savings;
    }
}
cout << "Done" << endl;
outFile << "Rectangle:" << endl  << "Total length = " << tLength << ", " << "Total width = " << tWidth << ", " << "Total area = " << tAreaRec << ", " << "Total parameter = " << tParameter << endl << endl
<< "Circle:" << endl << "Total radius = " << tRadius << ", " << "Total area = " << tAreaCirc << ", " << "Total circumference = " << tCircumference << endl << endl
<< "Person: " << endl << "Total number of persons = " << people << endl << "Total age = " << tAge << endl << "Total savings = " << tSavings << endl;
inFile.close();
outFile.close();
system("pause");
return 0;

}

例如,如果我的错误数据如下,我想捕获字符和字符串并返回0,但不知道如何解决这个问题。有人能指引我正确的方向吗?

10.45 aaaa
13.78
Jake Melon 45
7600
128 76.9
;
Mike Sander 23
800
15.9 43
w
David James i
87000.54

while循环结束后,您可以添加一个测试来检查while循环是否由于EOF或由于读取数据错误而终止。

while (inFile >> length >> width >> radius >> name1 >> name2 >> age >> savings) { ... }
if ( inFile.eof() )
{
   // No errors in reading data
}
else
{
   // Error in reading data.
   // Deal with error
}