Google Answers Logo
View Question
 
Q: C++: reading numbers from file into an array ( No Answer,   5 Comments )
Question  
Subject: C++: reading numbers from file into an array
Category: Computers > Software
Asked by: ironeagle_09-ga
List Price: $10.00
Posted: 05 Dec 2005 21:53 PST
Expires: 07 Dec 2005 13:31 PST
Question ID: 602008
I need to read a text file(format given below) in C++

filename:test.txt

3
1,2,3,4,5
2,1,3
3,4,2,1

I need to store the top number(3) in an variable(num).
The rest, I need to store in an 2D array set[i][j];
The number of lines in the text file can be anywhere 3 to 25 lines.

I need a simple C++ code to do this. It will help me if I can have the
code by tomorrow afternoon(12/6). I will tip well for a fully working
C++ code.

Thanks in advance.
Answer  
There is no answer at this time.

Comments  
Subject: Re: C++: reading numbers from file into an array
From: sarulan-ga on 06 Dec 2005 06:08 PST
 
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen("test.txt","rb");	
int num;
int *array[100]; /*assume maximum 100 numbers in a row*/
int test;
int i,j,k;
fscanf(fp,"%d",&num); /*get the top number*/
printf("num = %d\n",num);/*print the number*/
for(i=0;;i++)/*loop row*/
{
	for(j=0;;j++)/*loop column*/
	{
	if(fscanf(fp,"%d",&test)==-1) /*get the number till file ends*/
	goto end;		
	array[i][j]=test;	/*store it in array*/
	printf("array[%d][%d] = %d\n",i,j,array[i][j]); /*print it*/ 
	if((k=fgetc(fp))=='\n') /* if new line then goto next row*/
	break;	
	}
}
end:printf("All Done\n");/* Print all done*/
}
Subject: Re: C++: reading numbers from file into an array
From: ljbuesch-ga on 06 Dec 2005 06:57 PST
 
haha, my c++ skills aren't as ub3r l33t as his, but this gets the job done.

#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>

using namespace std;
#define MAX_LINES 25
#define MAX_IN_LINE 50

int main() {
  //open our file
  ifstream myfile ("test.txt");
  //initialize our array's
  int myarray[MAX_LINES][MAX_IN_LINE];
  //used for knowing how many numbers are stored in each array
  int totalargs[MAX_LINES];
  //rest of variables
  string line,tempnum;
  int end=0;
  int firstarg=0,secondarg=0;
  int num;

  //set all of our arrays to be zero'd out
  memset(myarray,0,MAX_LINES*MAX_IN_LINE);
  memset(totalargs,0,MAX_LINES);

  //make sure file is opened
  if (myfile.is_open()) {
    //get a line
    getline(myfile,line);
    //the first line is the number, so set it to num
    num=atoi(line.c_str());

    while(!myfile.eof()) {
      getline(myfile,line);
      //if there is a , in the line we have gotten
      while((end=line.find(',',0))!=string::npos) {
        //get the number before the ,
        tempnum=line.substr(0,end);
        myarray[firstarg][secondarg]=atoi(tempnum.c_str());
        secondarg++;
        //erase the part of the line we have gotten
        line.erase(0,end+1);
      }
      //we will have an extra number at the end after that loop
      //this gets that last number
      tempnum=line.substr(0,line.length());
      myarray[firstarg][secondarg]=atoi(tempnum.c_str());
      //set the number of args to our array
      totalargs[firstarg]=secondarg;
      firstarg++;
      //reset arg.
      secondarg=0;
    }
  } else {
    cout << "cannot open";
  }

  //this is extra, but it just shows you your variables and that
  //they really do have numbers in them.
  cout << "num: " << num << endl;
  for (int x=0;x<firstarg;x++) {
    cout << "Array " << x+1 << ": " << myarray[x][0];
    for (int y=1;y<=totalargs[x];y++) {
      cout << "," << myarray[x][y];
    }
    cout << endl;
  }
}
Subject: Re: C++: reading numbers from file into an array
From: sarulan-ga on 07 Dec 2005 06:35 PST
 
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen("test.txt","rb");	
int num;
int array[25][100]; /*assume maximum 100 numbers in a row*/
int test;
int i,j,k;
fscanf(fp,"%d",&num); /*get the top number*/
printf("num = %d\n",num);/*print the number*/
for(i=0;;i++)/*loop row*/
{
	for(j=0;;j++)/*loop column*/
	{
	if(fscanf(fp,"%d",&test)==-1) /*get the number till file ends*/
	goto end;		
	array[i][j]=test;	/*store it in array*/
	printf("array[%d][%d] = %d\n",i,j,array[i][j]); /*print it*/ 
	if((k=fgetc(fp))=='\n') /* if new line then goto next row*/
	break;	
	}
}
end:printf("All Done\n");/* Print all done*/
}
Subject: Re: C++: reading numbers from file into an array
From: ironeagle_09-ga on 07 Dec 2005 10:14 PST
 
ljbuesch-ga..I tried your program and it worked ..thank you for the
help.can u post the same as answer.
Subject: Re: C++: reading numbers from file into an array
From: firewireguy-ga on 07 Dec 2005 11:24 PST
 
If you want to actually use proper C++ throughout and not use C
functions and be limited by constant sized POD arrays (EVIL!) - no
bounds checking, not dynamic etc. then this is 100% C++ (AKAIK).  It
also doesn't use things like atoi() and instead converts the number
properly using istringstream >>



#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

#pragma warning(disable: 4786)

void Tokenize(const string& str,
			  vector<string>& tokens,
			  const string& delimiters = " ");

int main(int argc, char* argv[])
{
	int num;
	string str;
	//open the file (use forward slash to avoid accidentally using escape chars)
	fstream file_op("c:/test_file.txt",ios::in);
	//get the first digit on the first line
	if (!file_op.eof()) {
		getline(file_op, str);
		istringstream i(str);
		i >> num;
	}

	//create our vector that we will use
	vector<int> vecNumbers;
	vector<int>::const_iterator vecNumbersIt;
	vector< vector<int> > vecLines;
	vector< vector<int> >::const_iterator vecLinesIt;

	//will use a vector of strings for our Tokenise() function and then iterate
	//through it converting them to numbers
	vector<string> vecString;
	vector<string>::iterator vecStringIt;

	//dont reposition the file pointer, we are already on line two
	while(!file_op.eof()) {
		getline(file_op, str);
		vecNumbers.clear();
		vecString.clear();
		//split the line on the commas
		Tokenize(str, vecString, ",");
		//for each string in the vector convert it to a number -PROPERLY -
and put it in vecNumbers
		for (vecStringIt = vecString.begin(); vecStringIt !=
vecString.end(); ++vecStringIt) {
			istringstream i(*vecStringIt);
			int x;
			i >> x;
			vecNumbers.push_back(x);
		}
		//we have every number in the line in vecNumbers, now put the
numbers into the vecLine
		vecLines.push_back(vecNumbers);
	}
	//be nice and close the file
	file_op.close();

	//OUTPUT ONLY
	cout << num << endl;
	for (vecLinesIt = vecLines.begin(); vecLinesIt != vecLines.end(); ++vecLinesIt) {
		vecNumbers = *vecLinesIt;
		for (vecNumbersIt = vecNumbers.begin(); vecNumbersIt !=
vecNumbers.end(); ++vecNumbersIt) {
			cout << *vecNumbersIt << ",";
		}
		cout << endl;
	}
	return 0;
}

void Tokenize(const string& str,
			  vector<string>& tokens,
			  const string& delimiters /*= " "*/)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);
	
    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}




Hope this helps.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy