I need some help, fairly new to C++ and I know a little about C. What i am trying to do is get a txt file that looks like this

4 //first number tells how many rows are coming next.
3 54
2 51
9 32
2 34

what i want to do is get the numbers into a array so that i can use them later on in a function. Here is what i wrote so far, and is there a better way in C++.

# include <stdio.h>

void READFile(char* filename)
	int num;

FILE* inputfile;
if ((inputfile = fopen(filename, "r")) ==NULL)
printf("file not found, unable to open\n");


	fscanf( inputfile, "%d", num);
	int color[num];
	int value[num];
	for (int i = 0; i< num; i++);
		fscanf(inputfile, "%d","%d",  &color, &value);

8 Years
Discussion Span
Last Post by vmanes

Here's your code, translated in to C++.

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

void READFile(char* filename)
	int num;

	int color[100];  //make this large enough for any problem set
	int value[100];

	ifstream inputfile;

	inputfile.open( filename );
	if ( !inputfile )
		cout << "file not found, unable to open\n";
		return;  //added

	inputfile >> num ;

	int color[num];  //oops, not yet legal in C++
	int value[num];  //although array declaration with variables
			//is supported in some compilers
	for (int i = 0; i < num; i++);
		inputfile >> color[i] >> value[i];

Note that by declaring the color and value arrays in the function, they only exist in that function. Perhaps they should be declared in main( ) and passed to the function?

I don't think your C input was quite correct, you input to the address of the array, but never incremented to fill other array elements. Should that have been

fscanf(inputfile, "%d","%d",  &color[i], &value[i]);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.