I'm having trouble understanding this.
I want to make a function that reads from a file
and then outputs the info in a 2D array.
Here's what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12
void getfromfile()
{
cout << "Please enter a file name: ";
cin >> file[30][100];
myfile.open(file[30][100].c_str());
if(!myfile)
cout << "File does not exist." << endl;
myfile.close();
cout << file[30][100];
}
It looks like you are trying to read a filename into a 2d array which makes no sense. Then you want to output the filename to the screen. The file name should just be a std::string. Do you really want the user to specify the full path to the file via the console window or do you want to just define the file name as a constant within the program and then open the file using it? What type of info is in the file? If you want help reading the file into an array we need to know what is in the file.
Sorry, I should have been more specific. The user types in the file name like data.txt, which is assumed to exist where it's supposed to be. The file has a bunch of integers already in it.
I'll tell you exactly what each line of your code does:
1 2 3 4 5 6 7 8 9 10 11 12
void getfromfile()
{
cout << "Please enter a file name: ";
cin >> file[30][100]; // read from standard input to the 101st 31st element of the array -may cause overflow if the sizes are 30 and 100-
myfile.open(file[30][100].c_str()); // open the file with that given name
if(!myfile)
cout << "File does not exist." << endl;
myfile.close(); // close the file
cout << file[30][100]; // display the file name you got
}
Here is what you should have:
1 2 3 4 5 6
string name;
getline ( cin, name );
myfile.open ( name.c_str() );
for ( unsigned i = 0; i < 30; i++ ) // loop through the 1st dimension of the array
for ( unsigned j = 0; j < 30; j++ ) // loop through the 2nd dimension of the array
myfile >> file[i][j]; // read to each element of the array
Notice that you may want to check for failures when reading into the array and that if you want to display the array you should use nested loops similar tho that.
Ok, here's what I have. I'm having trouble understanding why the output is running all in one line like: 100000100000100000100000 instead of in array form.