jeudi 19 mars 2015

C++ How do I read numbers from a file and assign it to a respective place in an array?


I need to create a program that will read numbers from a file and place them into an array. I have most of my program mapped out. I am confused on how to use a loop in my main function to place the values into an array after reading them from the input file. Should I create a boolean or make a pointer?



My input file: There are 6 cols and 4 rows.

89 93 23 89 78 99
95 21 87 92 90 89
94 88 65 44 89 91
77 92 97 68 74 82

Code

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//Function prototypes
void openInputFile(ifstream &, string str);
void printArray();
int getTotal(int[], int, int);
int getAverage(int);
int getStandardDeviation();
int getRowTotal(int[], int);
int getHighestInRow(int[], int);
int getColumnTotal(int[], int);
int getHighestInColumn(int[], int);

const int COLS = 6;
const int ROWS = 4;
int main()
{
//Variables
int num;
int arr[ROWS][COLS] = {};

ifstream inFile;

string fileName = "C:\\Users\\Lisa\\Desktop\\a3_data.txt";

openInputFile(inFile, fileName); //Call to open input file

//For loop will read each value from file and place it in array
while (inFile >> num)
{
cout << num << " ";
}

//Close input file
inFile.close();

system("PAUSE");

return 0;
}
//end of main function

//To open input file
void openInputFile(ifstream &inFile, string fileName)
{
//Open the file
inFile.open(fileName);

//Input validation
if (!inFile)
{
cout << "Error to open file." << endl;
cout << endl;
return;
}
}
//end of OpenInputFile



Aucun commentaire:

Enregistrer un commentaire