我已经为它制作了一个代码,但它非常差。我想知道如何更快地获得所有整数和总和。谢谢:))
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int d, m, s, b = 0, l = 0, vm, vs, mv, ms;;
ifstream file("File.txt");
if (file.is_open())
{
file >> d;
cout << d << endl;
file >> m >> s;
cout << m << " " << s << endl;
b += m;
l += s;
file >> m >> s;
cout << m << " " << s << endl;
b += m;
l += s;
file >> m >> s;
cout << m << " " << s << endl;
b += m;
l += s;
file.close();
}
else cout << "File has not opened." << endl;
return 0;
}
答案 0 :(得分:1)
你想要达到的目标并不是很清楚。我假设您需要2个部分总和。您可以做的是将if
块的所有内容替换为:
file >> d; // read the first number
cout << d << endl;
while(file >> m >> s) // keep reading 2 numbers
{
b += m;
l += s;
cout << m << " " << s << endl;
}
无需手动关闭文件,析构函数将在程序结束时自动处理(范围)。