Example: data.txt File Content
1. Easy to burn
2 light, no pain, normal light
Use the C ++ fstream and Getline methods to read information into a two-dimensional array string data [] []
Method 1: (applicable to known rows and columns, separated by spaces or tabs)
# Include <fstream>
# Include <string>
Using namespace STD;
Void main ()
{
Ifstream ifile ("data.txt ");
String data [2] [6];
For (INT I = 0; I <2; I ++)
For (Int J = 0; j <6; j ++)
Ifile> data [I] [J];
Ifile. Close ();
}
Method 2: (the number of unknown rows and columns are separated by spaces)
# Include <fstream>
# Include <string>
# Include <vector>
Using namespace STD;
Typedef vector <string> VVS;
Void main ()
{
Ifstream infile ("data.txt ");
Infile> noskipws; // do not ignore the blank and read the '/N' at the end of each line.
// Determine the number of rows and columns. Data in each column in the file is separated by spaces.
Int row, Col, K;
Row = Col = 0;
Char CHR;
While (infile> CHR)
{
Switch (CHR)
{
Case '/N': // determines whether the character to be read is a line break
+ + Row; // if it is a line break, the number of rows + 1
Col = 0; // if it is a line break, the number of columns is cleared.
Break;
Case '': // determines whether the characters to be read are blank.
+ + Col; // The number of columns + 1
Break;
Default :;
}
}
Infile. Close (); // close a text file
Row ++; Col ++; // The number of rows and columns obtained by reading the file plus 1 is the actual number of rows and columns (Note: there are no blank lines at the end of the file)
Vvs data; // defines a two-dimensional string array.
Data. resize (row );
For (k = 0; k <row; k ++)
Data [k]. resize (col );
Ifstream infile2 ("data.txt ");
Int trow, tcol;
Trow = tcol = 0;
String str;
While (trow <row) // loop comparison, with the number of rows as the limit
{
While (tcol <col-1)
{
Getline (infile2, str, ''); // separate objects with spaces for Data Reading
Data [trow] [tcol] = str; // Save the data before the space to the corresponding string array.
Tcol ++; // The number of Columns after data is saved + 1
}
Getline (infile2, str, '/N'); // enter the carriage return as an object to determine whether a row ends.
Data [trow] [tcol] = str; // read the data before the carriage return to the corresponding string array.
Tcol = 0; // The number of columns is assigned to 1 to determine the next row.
Trow ++; // number of rows + 1
}
Infile2.close ();
}