Loading data into a vector from text-file

This is a discussion on Loading data into a vector from text-file within the C++ Programming forums, part of the General Programming Boards category; Hi I use the following piece of code to load a bunch of doubles into my vector: Code: #include <iostream> ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    140

    Loading data into a vector from text-file

    Hi

    I use the following piece of code to load a bunch of doubles into my vector:

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    ...
    
    
    	std::vector<double> velX;
    	double velTemp;
    
    	std::ifstream vX("vX.txt");
    	if(vX.is_open())
    	{
    		while(!vX.eof())
    		{
    			getline(vX, velTemp);
                velX.push_back(velTemp);
             }
    		vX.close();
    		}
    	else
    	{
    		cout << "Unable to open file." << endl;
        }
    However, my compiler says that getline is "an undeclared identifier". Isn't that what iostream is supposed to contain?

    Best,
    Niels.

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,684
    The getline() functions only work with C-strings, or std::string not doubles, try the extraction operator>>. Also you should not use eof() to control your entry loop as this will usually cause problems, use your extraction operation. This link may be of some interest: Basic C++input and output

    Jim
    Last edited by jimblumberg; 03-31-2012 at 03:44 PM.

  3. #3
    'Allo, 'Allo, Allo
    Join Date
    Apr 2008
    Posts
    611
    Quote Originally Posted by jimblumberg View Post
    The getline() functions only work with C-strings, or std::string not doubles
    The istream member function getline() only works on C-strings. The free function getline() from <string> works with std::strings.

    OP: neither getline reads doubles, so as jimblumberg pointed out the extraction operator e.g. while(vX >> velTemp) is the way forward.

  4. #4
    Registered User
    Join Date
    Aug 2009
    Posts
    140
    Thanks to both of you,

    Best.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-25-2011, 05:54 PM
  2. Loading Text File Resources
    By Brokenhope in forum Windows Programming
    Replies: 4
    Last Post: 10-11-2010, 04:32 AM
  3. Opening file and loading data into Vector
    By soopah256 in forum C++ Programming
    Replies: 4
    Last Post: 08-04-2009, 10:18 PM
  4. Help loading from text file!
    By Cherry65 in forum C++ Programming
    Replies: 8
    Last Post: 12-15-2008, 10:13 AM
  5. Loading text from file into struct
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 03-19-2002, 04:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21