Strings, Textfiles and Arrays

How does one store a file in an array(using fstream, strings etc), with say 1000 characters
and displays the content.......thanks

Last edited on
Why do you need the content in an array? You can directly display from the file.
Well, I need to store it in an array,
then using the array, code how many number of words are in the document, deleting a string from the document, inserting a string, all that...
Last edited on
You can try something like this:

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
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main()
{
    ifstream file;
    vector<string> v;

    file.open("input.txt");

    string s;
    file >> s;

    while (file)
    {
        v.push_back(s);
        file >> s;
    }

    file.close();
    
    cout << "There are " << v.size() << " words in the file.";

    return 0;
}
Thanks, Josue......
if I would use arrays, how would it be coded....thanks
If you want to use an array, then you will have to make two passes to the file: one to count the number of words in it, and the other to store the words in an array.

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
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    // Count the number of words in the file.
    ifstream file;
    int wordCount = 0;
    file.open("input.txt");
    string s;
    file >> s;
    while (file)
    {
        wordCount++;
        file >> s;
    }
    file.close();

    // Store the words in an array.
    string v[wordCount];
    wordCount = 0;
    file.open("input.txt");
    file >> s;
    while (file)
    {
        v[wordCount++] = s;
        file >> s;
    }
    file.close();
    
    // Display the contents of the array.
    for (int i = 0; i < wordCount; i++)
    {
        cout << v[i] << ' ';
    }

    return 0;
}
Very similar except that you need to know the maximum size of the file first or the content will be cut off. This one will read the first 100 lines from a file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream> 
#include <string>

using namespace std;

int main()
{
    ifstream fin("input.txt");
    string line[100];

    for (int i = 0; i < 100; ++i)
    {
        getline(fin, line[i]);
        if ( !fin.good() )
            break;
    }

    return 0;
}
Topic archived. No new replies allowed.