170: Import data from .txt file into a 2D array
#include <iostream>
#include <fstream>
#define maxlim 10 // set what should be the maximum number of row you wanna read
using namespace std;
int main()
{
string arr[maxlim][4]; // initializing array in which we will import data
ifstream file; // it must be ifstream not fstream
file.open("myfile.txt", ios::app); // set file name and ios::app will not overwrite file while writing it again
if (file.fail()) // if file does not open program will terminate
{
cout << "File opening filed\n";
return 1;
}
int rows = 0; // declaring rows
while (file.eof() == 0) // reading file till end of file
{
string temp_row = "";
getline(file, temp_row); // take line 1 of file as input in temp_row
if (temp_row == "") // if it is empty row you will skip to next row
{
rows++;
continue;
}
int column = 0;
string temp_col = "";
for (int j = 0; j < temp_row.length(); j++) // breaking row that we input into different values
{
if (temp_row[j] != ',') // if , does not occur keep adding character in temp_row
{
temp_col += temp_row[j];
}
else // if , occur save temp_row into 2D array
{
arr[rows][column] = temp_col;
temp_col = ""; // empty temp_col
column++;
}
}
rows++;
if (rows == maxlim) // if rows become equal to max limit, decrease row by one, show error message, break
{
rows--;
cout << "%%%%% (Error) %%%%%%%%%%% (Maximum memory reached)%%%%%%%%%%%" << endl;
break;
}
}
file.close(); // closing file
// Output 2D array
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j < 4; j++)
{
cout << arr[i][j] << ' ';
}
cout << endl;
}
return 0;
}
Data:
1122,2331,3232,umar,
3334,3232,1323,usman,
4444,32323,2231,mohib,
565,232323,323,abdullah,
666,42323,233,waleed,
1122,2331,3232,waheed,
3334,3232,1323,waseem,
1122,2331,3232,naseem,
3334,3232,1323,qasim,
1122,2331,3232,shahbaz,
3334,3232,1323,najam,
Precautions:
- In the data and in the code, there must be a common word terminator like in above code, it is a comma (,).
- Ending of each line must also be word terminator or else that word will not be imported.
Comments
Post a Comment