【发布时间】:2012-11-12 05:44:29
【问题描述】:
目前我正在尝试将双精度值存储到数组的索引中。据我所知,我这样做是正确的,但我一定是错的,因为由于某种原因,当我运行程序时,我得到了一些非常疯狂的数值。
我需要一些帮助来解决这个问题,在此先感谢。
ps:我认为显示的值基本上是最后存储的值 在那个特定的内存位置...
代码(如果您需要查看更多信息,请告诉我):
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <new>
using namespace std;
int INDEXES = 0;
string *names_Array;
double *rates_Array;
double *hours_Array;
void subscript(ifstream&, int&, string&, double&, double&);
void arrayInput(ifstream&, string [], double [], double[],
string&, double&, double&);
int main()
{
string names;
double rates;
double hours;
string filename("employee sample file.txt");
ifstream employeeInfo(filename.c_str());
if (employeeInfo.fail())
{
cout << "Sorry, file was not successfully opened. "
<< "Please make sure your file exists and\n"
<< "re-run the program." << endl;
}
subscript(employeeInfo, INDEXES, names, rates, hours);
names_Array = new string[INDEXES];
rates_Array = new double[INDEXES];
hours_Array = new double[INDEXES];
arrayInput(employeeInfo, names_Array, rates_Array, hours_Array,
names, rates, hours);
cout << rates_Array[0] << endl
<< rates_Array[1] << endl
<< rates_Array[2] << endl
<< rates_Array[3] << endl
<< rates_Array[4] << endl;
employeeInfo.close();
system("pause");
return 0;
}
void subscript(ifstream& employeeInfo, int& INDEXES,
string& names, double& rates, double& hours)
{
while(!employeeInfo.eof())
{
employeeInfo >> names >> rates >> hours;
INDEXES++;
}
}
void arrayInput(ifstream& employeeInfo, string names_Array[], double rates_Array[],
double hours_Array[], string& names, double& rates, double& hours)
{
int i = 0;
string line;
while(getline(employeeInfo, line))
{
employeeInfo >> names >> rates >> hours;
names_Array[i] = names;
rates_Array[i] = rates;
hours_Array[i] = hours;
i++;
}
}
输入文件(请忽略双倍行距):
克林顿 10.00 10
林肯5.00 50
华盛顿 32.00 35
肯尼迪 4.99 45
尼克松 10.00 25
输出:
-6.27744e+066
-6.27744e+066
-6.27744e+066
-6.27744e+066
-6.27744e+066
输出应该是:
10.00
5.00
32.00
4.99
10.00
【问题讨论】:
-
你的代码有点奇怪。为什么要引用函数的参数?但这并没有错。该错误位于您未发布的代码中。也许您可以显示调用函数的代码,以及打印值的代码。
-
你怎么称呼
arrayInput? -
你的代码中是否还有这个:
int INDEXES = 0; string *names_Array = new string[INDEXES];from your previous question? -
是的,我会的,给我一秒钟,我会把它全部放好
-
同意 jrok 的观点,之前的代码有一些严重的误解。我想你还有他们。问题比这个功能严重得多。看起来数组索引是您确实了解的事情之一。不幸的是,I/O 和动态分配是你不了解的。