1 Replies - 708 Views - Last Post: 21 November 2014 - 04:21 PM Rate Topic: -----

#1 fruits   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-November 14

How do I store the values from a file to an array in C++

Posted 21 November 2014 - 03:23 PM

I'm trying to read values from a file to store them in an array in C++ and then output the values in a table format for everyday of the month: morning, noon, evening and night
My text file looks something like this:
38
210
14
3
214
222
82
176
225
.
.
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
using namespace std;

struct dailyReadings{

	int morningReading;
	int afternoonReading;
	int eveneningReading;
	int nightReading;

} carbonMonoxide [31];


int main()
{ 
	ifstream inputFile;

	string myArray[124];

	inputFile.open("readings.txt");

	if(!inputFile.is_open()){
		cout << "Failed to open file" << endl;
	}else{
		cout << "File opened successfully" <<endl;
		while(!inputFile.eof();)/>/>{

                        // here im reading the values but how do i loop through them to get the morning reading for carbon monoxide every 4 values from the file
			getline(inputFile, MyArray[i]);
			cout << myArray[i] << endl;
		}
	}
	
// i'm getting stuck here 
	for (n=0; n<31; n++)
	{
		cout << "Morning Readings are ";
		getline (inputFile, carbonMonoxide[n].morningReading);
		cout << "Afternoon Readings are: ";
		getline (inputFile, carbonMonoxide[n].afternoonReading);
                cout << "Evening Readings are: ";
		getline (inputFile, carbonMonoxide[n].eveningReading);
		cout << "Night Readings are: ";
		getline (inputFile, carbonMonoxide[n].nightReading);	
}

	inputFile.close();
    cin.get();
    return 0;
}




Is This A Good Question/Topic? 0
  • +

Replies To: How do I store the values from a file to an array in C++

#2 #define   User is offline

  • Duke of Err
  • member icon

Reputation: 1853
  • View blog
  • Posts: 6,671
  • Joined: 19-February 09

Re: How do I store the values from a file to an array in C++

Posted 21 November 2014 - 04:21 PM

Hi, you have a semicolon improperly placed here :-

	while( !inputFile.eof(); ) {




The structure is called DailyReadings, so you don't really need to name the variables <something>Reading just morning etc would do.

You can read the number from the file stream into a numeric variable, even into the member variable of the struct.

 input >> carbonMonoxide[5].morning;


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1