2d array and text files

need to bring in numbers from text file into 2d array

Page 1 of 1

2 Replies - 6399 Views - Last Post: 08 November 2010 - 01:02 PM Rate Topic: -----

#1 ngxcrunner  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 13-October 08

2d array and text files

Posted 08 November 2010 - 12:39 PM

i am having trouble bringing in numbers from a text file into a 2d array as part of an assignment. I just need some help with this part most of it i can do myself.
here is what i have so far

#include<iostream>
#include<fstream>
using namespace std;

void main(){
	int x,y;
	double sales_array[150][25];
	ifstream in ("sales.txt");
	ofstream out;
	
	if (in.is_open()){
	while (in.good()){

	for(x=0;x<=150;x++){			
        

		for(y=0;y<=25;y++){       
		

        }
	}

	
}
}




}




Is This A Good Question/Topic? 0
  • +

Replies To: 2d array and text files

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6066
  • View blog
  • Posts: 23,526
  • Joined: 23-August 08

Re: 2d array and text files

Posted 08 November 2010 - 12:46 PM

For starters,
double sales_array[150][25];
for(x=0;x<=150;x++){
    for(y=0;y<=25;y++){

Arrays are indexed from 0 to length - 1. By using <= in your loop conditions, you are going one past the end of the array, which means writing into memory you don't "own".

Secondly, void main() is ALWAYS WRONG in C++, as per the creator of C++ himself. It's int main().

Third, what exactly is the issue? Other than the above you seem setup OK for your task.
Was This Post Helpful? 0
  • +
  • -

#3 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 162
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: 2d array and text files

Posted 08 November 2010 - 01:02 PM

A quick example on how to read from files:
Text File (test.txt):
10 20 30
40 50 60
70 80 90



#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    int num;
    ifstream fi("test.txt");
    if(!fi) {
        cout<<"Cannot open file.Bye";
        return 1;
    }
    while(fi>>num) { //Reads number till EOF
        cout<<num<<endl;
    }
    return 0;
}



Check out the file tutorial - link.

This post has been edited by Munawwar: 08 November 2010 - 01:06 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1