Creating array of strings from txt file with pointers

I am trying to create a program that reads a text file into an array of strings. I do have to use pointers since the size of the array is determined first by reading the text file (first line of file is size or array).

The code as it is is not compiling. The list of errors is long and includes things like "no match for operator >>" in reference to inFile >> rows.

I realize there are other ways to create an array of strings, but since this is for a class I need to continue to use the for loop.

Thanks for your help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
  #include <string>
  #include <fstream>
  
  int main() 
  {
     std::string** arr = nullptr;
     int rows = 0; 
     std::string myFile = "data.txt"; 
     std::ifstream inFile; 
     inFile.open(myFile); 

     inFile >> rows; \\first line of txt file is number of rows
     for (int i = 0; i < rows; i ++) 
     {
           inFile >> arr[i]; 
           std::cout<<"\n"<<arr[i];
     }

     for (int i = 0; i < rows; i++) 
     {
          delete[] arr[i];
     }
     delete[] arr;
     inFile.close();
     return(0);
  }
arr[i] is a pointer to a std::string.
You are trying to access a nullptr.

1
2
3
inFile >> rows;
std::string* arr = new std::string[rows];
// ... 
I've made the changes you said and am still getting similar errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
  #include <string>
  #include <fstream>
  
  int main() 
  {
     std::string** arr = nullptr;
     int rows = 0; 
     std::string myFile = "data.txt"; 
     std::ifstream inFile; 
     inFile.open(myFile); 

     inFile >> rows; 
     std::string* arr = new std::string[rows];
     for (int i = 0; i < rows; i ++) 
     {
           inFile >> arr[i]; 
           std::cout<<"\n"<<arr[i];
     }

     for (int i = 0; i < rows; i++) 
     {
          delete[] arr[i];
     }
     delete[] arr;
     inFile.close();
     return(0);
  }

Topic archived. No new replies allowed.