user3069453
user3069453

Reputation: 25

Storing a data from file into a two dimensional array in C++

I am having the following code in C++

char *Names[];
int counter=0;
int _tmain(int argc, _TCHAR* argv[])
{
    int data;
    ifstream fileX;
    fileX.open("myfile",ios::in);
    assert (!fileX.fail( )); 
    fileX >> data; 
    while(fileX!=eof())
    {
        createNamesList(data);
        fileX >> data;
    }
    return 0;
}

void createNamesList(char *tmp)
{
    Names[counter] = tmp;
    counter++;
}

What I want to read the data from file line by line and store each line in a two dimension array char* Names[], so that a whole list is saved with me. the size of data in each line is variable length as well as number of lines are; like

 Name[0] ="Data from Line 1"
 Name[1] ="Data from Line 2"
 Name[2] ="Data from Line 3"
 Name[3] ="Data from Line 4"
 .
 .
 .

The above code give me the following error

error LNK2001: unresolved external symbol "char **Names" (?Names@@3PAPADA)

Your help will be appreciated.

Upvotes: 0

Views: 619

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490108

The error message you're seeing is barely the tip of the iceberg in the problems with this code.

I'd recommend using the std::vector and std::string classes included with your compiler to make this a bit simpler.

int main() {
    std::ifstream fileX("myfile");

    std::vector<std::string> Names;

    std::string temp;
    while (std::getline(fileX, temp))
        Names.push_back(temp);
    return 0;
}

Upvotes: 2

Related Questions