0

我需要编写一个程序,将 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。

4

2 回答 2

1

这些很可能是垃圾值,并确保文件 homework3.txt 正确并在程序中正确打开。

于 2013-09-18T20:19:43.623 回答
1

I/O 是经常中断的东西,因为计算机并不擅长猜测。因此,您确实应该检查 I/O 操作是否成功:

if ( inFile >> num1 >> num2 >> num3 >> num4 >> num5 )
{
  // Worked !
}
else
{
  // Failed ! Something is wrong, and C++ won't guess.
}

其实你也应该检查一下是否open成功。文件是否在正确的目录中?或者它可能在上一个练习的目录中?

于 2013-09-18T20:20:39.907 回答