我正在努力完成我的 C++ 类(class)的作业。我不是在寻找为我完成的作业,但我已经陷入僵局,而且我的教授不是最擅长回复电子邮件的人。她有很多事情要做,所以这是可以理解的。
我正在创建一个程序来从输入文件中读取数据。数据包括员工姓氏、工作小时数和每小时工资率。我的问题是我需要将这些信息放入两个并行数组中。如果我能弄清楚该怎么做,我可以自己完成作业,但我确实用谷歌搜索过,并观看了我能找到的所有视频,但无济于事。
Here is the input data:
Smith 40 10.00
Jackson 25 8.00
Hill 35 10.00
Withers 28 7.25
Mills 32 7.55
Myers 50 10.25
Johnson 45 10.50
Mcclure 38 9.50
Miller 42 8.75
Mullins 40 10.75
更新:我已经编辑了我的代码并接近结果,我需要继续我的项目的下一步。我已经编辑了我如何从我拥有的文件中读取和初始化数据。然而,在我的专栏之间,我得到了一个奇怪的数字序列。
Smith
-9.25596e+61
-9.25596e+61
-9.25596e+61
40
-9.25596e+61
-9.25596e+61
-9.25596e+61
10.00
-9.25596e+61
-9.25596e+61
-9.25596e+61
Jackson
-9.25596e+61
7.25
-9.25596e+61
25
-9.25596e+61
-9.25596e+61
-9.25596e+61
8.00
-9.25596e+61
-9.25596e+61
-9.25596e+61
Hill
-9.25596e+61
-9.25596e+61
-9.25596e+61
35
-9.25596e+61
-9.25596e+61
-9.25596e+61
10.00
-9.25596e+61
-9.25596e+61
-9.25596e+61
以下是我修改后的代码。
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
const int NOFROWS = 10;
const int NOFCOLS = 3;
void readFile(ifstream& infile, string X[], double y[][NOFCOLS]);
void print(ifstream&infile,ofstream& outfile, string x[], double y[] [NOFCOLS]);
int main()
{
//variables
string names[20];
double wages[NOFROWS][NOFCOLS];
ifstream incode;
ofstream outcode;
incode.open("employeeinformation.txt");
outcode.open("results.txt");
if (!incode)
{
cout << "No data" << endl;
system("pause");
return 1; //if loop to terminate program if unable to open file
}
cout << fixed << showpoint << setprecision(2) << endl;
readFile(incode, names, wages); //calls function readFile
print(incode,outcode, names, wages);
incode.close();
outcode.close();
system("pause");
return 0;
}
//Function to read file and input information into array.
void readFile(ifstream& infile, string x[], double y[][NOFCOLS])
{
//local variables, used as counters for while loop.
int r = 0;
int c = 0;
for (r = 0; r < NOFROWS; r++)
infile >> x[r]; // gets information from file for position
infile >> y[r][c];
//r++; //counter to increase position value
for (c = 0; c < NOFCOLS; c++)
{
infile >> y[c][r];
}
void print(ifstream&infile, ofstream& outfile, string x[], double y[] [NOFCOLS])
{
cout << setw(10) << "Names" << setw(10) << "hours" << setw(10) << "wages";
for (int r = 0; r < NOFROWS; r++) {
outfile << x[r] << " " << endl;
for (int c = 0; c < NOFCOLS; c++)
{
outfile << setw(10) << y[r][c] << " " << endl;
}
}
}
最佳答案
您似乎打开文件一次,但尝试读取其内容两次。
readFile(incode, names); // reads incode until all data is read
readFile2(incode, wages); // reads from the same incode, that has all data already expended
例如,尝试关闭
和打开
文件,或者在第二次调用之前将读取指针移动到开头,或者更好的是重构 RAII 文件管理代码。
关于c++ - 使用两个并行数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091401/