Reading txt file into an array of strings
Nov 12, 2016 at 1:09am UTC
Hello, I've been trying to read a txt file into an array of strings for quite some time. There are a long list of errors but most of them say things similar to "no match for operator>>".
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; \\first thing in txt file is number of rows to follow
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);
}
Nov 12, 2016 at 1:13am UTC
I ended up figuring it out. Here is the correct code that runs.
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
#include <iostream>
#include <string>
#include <fstream>
int main()
{
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.