【发布时间】:2017-04-07 01:05:30
【问题描述】:
我目前正在为我的一个课程做一个项目,我们不允许使用指针或向量(很遗憾),我无法获得正确的数组输出。 我得到了一个包含 81 行和 2 列的文件 (第 1 列列出 X 值,第 2 列包含 Y 值)。第一行是列标题,因此它们被忽略。 我必须创建一个函数,将数据读入并行的一维数组(一个用于 X 值,一个用于 Y 值)。我让函数正常工作,如果我在从文件中读取数据的同一个 while 循环中输出数组,一切都很好。但是,当我回去尝试在 main 中输出它们时,我只会得到一堆废话。 到目前为止,这是我的代码:
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
//Function Prototype for readFile
void readFile(double oneDforX[], double oneDforY[]);
//Declare named constant for max number of rows
const int MAX_ROWS = 100;
int main()
{
//Declare two 1D array to hold data for X and Y
double oneD_ForXValues[MAX_ROWS];
double oneD_ForYValues[MAX_ROWS];
//Call function readFile to fill arrays
readFile(oneD_ForXValues, oneD_ForYValues);
/*
This is where I'm having the problem, when the arrays are
sent back to main I can't get the data to output correctly.
I tried this for the X array:
for (int i = 0; i < 80; i++)
{
cout << oneD_ForXValues[i] << end;
}
**This did not work, my output was something like this:
3.5 //The last number in the array
0
0 //Then a bunch of zeros all the way to the end
0
Any and all help is greatly appreciated! Thanks!
*/
return 0;
}
//Function Header for readFile function
void readFile(double oneDforX[], double oneDforY[])
{
//Declare file stream object and open file
ifstream dataIn;
dataIn.open("dataFile.txt");
//Loop counter
int count = 0;
//If opening file does not fail, execute
if (!dataIn.fail())
{
//Ignore first line, column titles
dataIn.ignore(80, '\n');
//While loop to read in data
while (!dataIn.fail())
{
dataIn >> oneDforX[count] >> oneDforY[count];
}
}
//If the file failed to open
else
{
cout << "An error occurred opening the file." << endl;
}
//Close the file
dataIn.close();
}
//Back to main
【问题讨论】:
标签: c++ arrays function file-io