gpt4 book ai didi

C++ infile提取检查是否为int

转载 作者:行者123 更新时间:2023-11-28 06:01:55 24 4
gpt4 key购买 nike

我是 C++ 的新手,不知道从哪里开始,或者是否可能,但我正在尝试检查长度、宽度、半径等是否实际上是 double ,如果不是返回 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
}

关于C++ infile提取检查是否为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33110720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com