我需要编写一个程序,将 5 个浮点数存储到一个文件中,然后编写第二个程序来读取这些数字并显示它们。我正在使用 C++ Microsoft Visual Studio Express 2012。
这是程序1:
// This program obtains 5 floating point numbers from the user,
// then saves these numbers to a file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Define Variables
double num1;
double num2;
double num3;
double num4;
double num5;
ofstream outputFile;
outputFile.open("homework3.txt");
// Get 5 floating point numbers
cout << "Please enter 5 floating-point numbers, all separtated by a space."<<endl;
cin >> num1 >> num2 >> num3 >> num4 >> num5;
// Store these numbers to the file
outputFile << num1 << endl;
outputFile << num2 << endl;
outputFile << num3 << endl;
outputFile << num4 << endl;
outputFile << num5 << endl;
// Close the file
outputFile.close();
cout << "Thank you!";
cin.ignore();
cin.get();
return 0;
}
我可以找到显示我输入的数字的文本文件。
然后是程序2:
// This program opens a file previously created, and displays
// the numbers and the sum of these numbers.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// Define Variables
ifstream inFile;
double num1;
double num2;
double num3;
double num4;
double num5;
// Open the file from program 1
inFile.open("homework3.txt");
// Read and Display the Numbers
inFile >> num1 >> num2 >> num3 >> num4 >> num5;
cout << num1 << endl << num2 << endl << num3 << endl << num4 << endl << num5 << endl;
inFile.close();
cin.ignore();
cin.get();
return 0;
}
我省略了关于查找总和的部分,因为它一开始对我来说没有正确显示。
当我运行这部分时,我得到
-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061。