c++文件提取检查是否为int
c++ infile extraction checking if int
我对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
}
相关文章:
- 是否可以从int转换为enum类类型
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 是否可以保证按字节的零 int 是零的表示形式?
- 是否可以将无符号 int 的最大值转换为 int 并将结果转换为 -1?
- 将uint8_t转换为已签名的 int 是否至少有时不正确?
- 判断 int 是否在 C++ 中赋值的任何优雅方法
- 从std::round转换为int是否安全
- 有没有办法检查int是否不等于数组中的所有值?(C )
- "!" "== 0"是否检查 int 是否是 0 的好做法?
- 从函数返回向量<向量<int>>是否会调用 C++11 中的任何移动构造函数
- 确定 int 是否包含特定数字的函数出现问题
- int 是否有运算符==
- 确定 int 是否不为 0,没有 if 语句
- 本地引用int是否有任何好处
- 在C++中,函数定义的int a[]和int*a是否相同
- 在C++中递增未初始化的 int 是否安全
- 将string映射到int是否可能比使用hashmap更快?
- Int a=1, a || 1是否为常量表达式
- ' int a = 0, b = a '是否有未定义的行为?
- 将本机方法定义为公共本机synchronized int doSum(int a, int b)是否正确?