How to load strings into dynamic array and concatenate them?

Write your question here.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
 #include <string>
#include <fstream>
#include <iostream>
 
using namespace 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.
Last edited on
Updated OP with new code, that takes each word and puts it into a dynamic array, I still need help though if anyones willing to help me. Thanks
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
Topic archived. No new replies allowed.