hoox2 said:
Hi everybody,
I am a c++ student, I have got stuck with this question:
How can I input a text file with name list into a 2-dimensional array?
(Don't suggest me to use vector or something else, this is my assignment
requirement.)
I have used
in_file.getline(array_name, max_size_of_each_row)
but it just doesn't work.
Pls help.
Regards,
Ho
Depends on the organisation of the input data and whether you
are using strings or character arrays (i.e. C-strings).
Here is a fragment for reading strings into a two dimensional
array. Missing code and error resolution is left to the
reader (don't post corrections).
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib.h>
using std::string;
using std::getline;
using std::ifstream;
using std::cerr;
int main(void)
{
const unsigned int MAX_COLS = 5;
const unsigned int MAX_ROWS = 7;
string string_array[MAX_COLS][MAX_ROWS];
ifstream data_file("data file name goes here");
if (!data_file)
{
cerr << "Can't open datafile.";
return EXIT_FAILURE;
}
for (unsigned int col = 0; col < MAX_COLS; ++col)
{
for (unsigned int row = 0; row < MAX_ROWS; ++row)
{
if (!getline(data_file, string[col][row], '\n'))
{
cerr << "Premature end of file reached."
cerr << "Rows read: " << row << "; columns: "
<< col;
data_file.close();
return EXIT_FAILURE;
} // End: if getline
} // End: for each row
} // End: for each column
data_file.close();
return EXIT_SUCCESS;
}
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book