Thread: Putting strings from a file into a vector

  1. #1
    Unregistered
    Guest

    Putting strings from a file into a vector

    Hi,

    I'm having a problem filling a vector with strings read as lines from a file. My vector has been declared:

    vector <char*> stringVector;

    and I can fill it fine with

    stringVector.push_back("test");
    stringVector.push_back("test1");

    and so on...

    However when I read from a file:

    ifstream fin(filename);

    fin.getline(tempString, 150);
    stringVector.push_back(tempString);

    The vector is not filled properly, it's length is increased but the elements do not become what tempString contains. I know tempString is getting the lines of the file because I debugged using

    fin.get(tempString, 150);
    cout << tempString;

    I also thought about setting the first element of tempString to a null terminator after each time it's been pushed onto the vector, this has no effect.

    Please can someone help, it's driving me mad!

  2. #2
    Unregistered
    Guest
    char stringTemp[150];
    vector<char*> vc;
    vc.push_back(stringTemp);

    you actually don't push the string in the vector but the address
    of its first element:&stringTemp[0];
    That's what the name of the array means.
    Use the new operator instead to allocate memory.

    an example:

    #include <iostream>
    #include <fstream>
    #include <vector>

    using namespace std;

    int main()
    {
    char stringTemp[150];
    char* cp=stringTemp;
    int i;
    vector<char*> vc;
    for(i=0;i<3;i++)
    {
    cin>>stringTemp;
    vc.push_back(stringTemp);
    }
    for(i=0;i<3;i++)
    {
    cout<<vc[i]<<endl;//wrong result
    }

    vc.clear();
    cout<<endl;

    for(i=0;i<3;i++)
    {
    cin>>stringTemp;
    char* cp=new char[strlen(stringTemp)+1];
    strcpy(cp,stringTemp);
    vc.push_back(cp);
    }

    for(i=0;i<3;i++)
    {
    cout<<vc[i]<<endl;//right result
    }

    for(i=0;i<3;i++)
    {
    delete[] vc[i];
    }
    return 0;
    }

    or you can use vector<string>.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. vector of pointers
    By gamer4life687 in forum C++ Programming
    Replies: 3
    Last Post: 09-26-2005, 10:49 PM
  4. Putting strings into an array from a text file.
    By JLan in forum C Programming
    Replies: 5
    Last Post: 11-20-2003, 07:34 PM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM