2015-10-13 70 views
0

我对C++相当陌生,不知道从哪里开始或如果它甚至可能,但我试图检查长度,宽度,半径等是否实际上双打,如果他们不返回0C++ infile抽取检查是否int

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 
+0

欢迎来到Stack Overflow!为了获得良好的回应,这里有几件事要记住。 1)假设你需要自己编写所有的代码。我们通常只会指出你正确的方向。 2)你试过了什么? (Google那句话)。我们需要看到你解决这个问题的尝试。 3)确保你已经彻底检查过文档和搜索引擎。如果其他人以这种方式找到了答案,你会得到一个简略的“RTD”或“LMGTFY”以及大量的downvotes。 – CodeMouse92

回答

1

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 
}