I want to read a .txt file.
.txt file will have N-rows and M-cols.
Each word present in the txt file will have varying length.
Sample txt file:
Suppose N = 4 rows
Suppose M = 5 cols
content of txt file:
aa bbb cc dddddddd eeee
aa bbbbbbbbbbbb cc ddddddddddd eeee
aaaaaaaaaa bb cc d e
a b c d eeee
What I have to do:
I have to store these strings into a 2D array of strings such that it looks like this:
arr[4][5] =
[aa bbb cc dddddddd eeee]
[aa bbbbbbbbbbbb cc ddddddddddd eeee]
[aaaaaaaaaa bb cc d e ]
[a b c d eeee]
I know how to create dynamic 2D array of integer and its working fine:
int** arr;
int* temp;
arr = (int**)malloc(row*sizeof(int*));
temp = (int*)malloc(row * col * sizeof(int));
for (int i = 0; i < row; i++)
{
arr[i] = temp + (i * col);
}
int count = 0;
//setting values in 2-D array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j] = count++;
}
}
But, when I am trying to do the same thing for strings, its crashing.
string** arr;
string* temp;
arr = (string**)malloc(row*sizeof(string*));
temp = (string*)malloc(row * col * sizeof(string));
for (int i = 0; i < row; i++)
{
arr[i] = temp + (i * col);
}
//setting values in 2-D array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j].append("hello"); // CRASH here !!
}
}
How to store each words in an array??
Aucun commentaire:
Enregistrer un commentaire