我需要编写一个程序,将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。
答案 0 :(得分:1)
最有可能这些是垃圾值,并确保文件homework3.txt正确并在程序中正确打开。
答案 1 :(得分:1)
if ( inFile >> num1 >> num2 >> num3 >> num4 >> num5 )
{
// Worked !
}
else
{
// Failed ! Something is wrong, and C++ won't guess.
}
实际上,您还应该检查open
是否成功。该文件是否在正确的目录中?或者它可能在上一个练习的目录中?