Seeding a 2D array from a file

So I have a file that has 11 columns. The first is a column that says "Student 1, Student 2, Student 3, etc.," The next 10 columns are just answers in a multiple choice exam. I'm wanting to seed it into a 2D array that has 35 rows and 11 columns. How can I set it up to go into the array? Here's what I tried so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  int main()
{
	string x;
	infile.open("exam.txt");

	string answers[35][11];

	if (infile.is_open())
	{
		for (int i = 0; i < 35; i++)
		{
			for (int j = 0; j < 11; j++)
			{
				infile >> answers[i][j];
			}
		}
	}
}
Last edited on
Hello Elarionus,

Without seeing the exact input file the code looks like it should work.

Post the input file and I will check it out.

Andy
Here is the link to the text file I'm using.

https://1drv.ms/t/s!AhreWSu1pf2XiOpKNQdkc-HPhliggQ

Right now, I'm trying to figure out how to pass it to another function to print the values.
you may want to set a delimiter after each result such as A,B,C
Hello Elarionus,

The program is OK except that you did not set up the file stream right. This would work better for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>
#include <fstream>

constexpr int MAXROW{35};
constexpr int MAXCOL{11};

int main()
{
	std::string x;
	std::ifstream infile;  // <--- Added.
	
	infile.open("exam.txt");

	std::string answers[MAXROW][MAXCOL];

	if (infile.is_open())
	{
		for (int i = 0; i < MAXROW; i++)
		{
			for (int j = 0; j < MAXCOL; j++)
			{
				infile >> answers[i][j];
			}
		}
	}

	return 0;  // <--- Not necessary, but good programming.
}


To pass the array to a function FunctionName(answers);. And in the function definition void FunctionName(std::string answers[][MAXCOL]). Giving a size on the first dimension is not necessary, but the second dimension must have a value.

The constant variables at the beginning allow you to change four places in the program by only changing the value of two variables. Makes it easier to find and change.

Hope that helps,

Andy
Ah, my mistake, the thing you added is right after my "include" section, before int main. I have it in there. Thank you! I'll have to keep practicing calling to other functions, whether it's arrays or regular things. I've been struggling consistently with it, and a massive test is coming up Friday. I'll make sure to put your information to good use! Thanks!
Topic archived. No new replies allowed.