Newbie question: read in part of text file, extract data into vector

Discussion in 'C++' started by RobBobSmith, Oct 5, 2010.

  1. RobBobSmith

    RobBobSmith New Member

    Joined:
    Oct 5, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hello all,

    I have a text file called: concentrations.dat

    The file contains a lot of different data. Here's the data that I'm interested in:

    # ET: list of elements

    'Cu' 'C' 'Sr' 'He' 'Mg' 'O' 'Cr'

    What I want to do is read the elements into a vector called elementVector. So I would end up with Cu, C, Sr, He, Mg, O, and Cr as elements of the vector without the ' symbols.

    Can anyone tell me how to do this? An example would be much appreciated. I have had no success with using ifstream. I can read in an entire file, but I can get parts of it out!

    I could either read in the entire file or only read in the part that I wrote above. Then I would need to get the elements, while discarding the ' symbols.

    I need to do this because I have written a program for doing calculations that needs to know which chemical elements are involved.

    Thanks for any help.
     
  2. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in
    I think that itz better not to go 4 vector for such a small thing. But still u want to implement with the help of vector then i can give u an algorithm for the same....
    Code:
    1)create a string vector...
    2) then open the file.
    3) create a string template variable...
    4) read the element one by one using that string variable...
    
    ohk let me more specific:-
    Code:
    std::vector<std::string>  eVector;
        std::ifstream in("concentrations.dat");
        std::string s;
        while( std::getline(in, s) )
        {
            if( line == "<et>" )
            {
                std::getline(in,s);
                stringstream st;
                st << s;
                std::string word;
                while( std::getline(st,word,'\'' ))
                {
                    size_t pos = word.find('\'');
                    if( pos != string::npos )
                        word.erase(pos,1);
                    eVector.push_back(word);
                }
     
            }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice