Search code examples
c++arrayspointersdynamic-allocation

Dynamically Allocating Array With Datafile


On a C++ project, I have been trying to use an array to store data from a textfile that I would later use. I have been having problems initializing the array without a size. Here is a basic sample of what I have been doing:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    int i = 0;
    ifstream usern;
    string data;
    string otherdata;
    string *users = nullptr;


    usern.open("users.txt");

    while(usern >> otherdata)
        i++;

    users = new (nothrow) string[i];

    for (int n = 0; usern >> data; n++)
    {
        users[n] = data;
    }


    usern.close();
    return 0;
}

This is a pretty rough example that I threw together. Basically I try to read the items from a text file called users.txt and store them in an array. I used pointers in the example that I included (which probably wasn't the best idea considering I don't know too much about poniters). When I run this program, regardless of the data in the file, I do not get any result when I try to test the values by including cout << *(users + 1). It just leaves a blank line in the window. I am guessing my error is in my use of pointers or in how I am assigning values in the pointers themselves. I was wondering if anybody could point me in the right direction on how to get the correct values into an array. Thanks!


Solution

  • Try reopening usern after

        while(usern >> otherdata)
        i++;
    

    perhaps, try putting in

    usern.close();
    ifstream usern2;
    usern2.open("users.txt");
    

    right after that.

    There may be other issues, but this seems like the most likely one to me. Let me know if you find success with this. To me it appears like usern is already reaching eof, and then you try to read from it a second time.

    One thing that helps me a lot in finding such issues is to just put a cout << "looping"; or something inside the for loop so you know that you're at least getting in that for loop.

    You can also do the same thing with usern.seekg(0, ios::beg);