#include <string>
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
ifstream infile;
int index = 0;
string singleWord;
infile.open("text.txt");
if (!infile.good())
{
cout << "Error, could not open the file!\n" << endl;
infile.clear();
return -1;
}
while (!infile.eof()) //to figure out size of array
{
infile >> singleWord;
index++;
}
string* strings = new string[index];
infile.close(); //to restart the file at the first word
infile.open("text.txt");
if (!infile.good())
{
cout << "Error, could not open the file!\n" << endl;
infile.clear();
return -1;
}
int count = 0;
while (!infile.eof()) //if not at end of file, continue reading numbers
{
count++;
infile >> strings[count];
}
infile.close(); //close file
return 0;
}
I have a textfile that has 3 lines spaced like this:
Arrays are quite difficult.
They are fun to learn however.
I haven't showered in 4 days.
I want to load each word/line into a dynamic array, and concatenate each line and output it to another file and to the screen. So the lines look like this in the end:
Arrays are quite difficult. They are fun to learn however. I haven't showered in 4 days.
Dynamic arrays are somewhat misleading because a fixed size still has to be declared at run-time when you use the new operator and in this case you can only do that when you've counted the number of words in the file. So
1. count the # of words in the file
2. dynamic array with new and # of words
3. then re-read the file and input into array
Alternatively if you want a really dynamic container that expands/contracts as required use std::vector