Thread: Read numbers from file to std::vector

  1. #1
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Question Read numbers from file to std::vector

    Hello,
    how to read all numbers from a file to std::vector?

    I have tried this one:
    Code:
    ifstream in;
    vector numbers;
    
       .
       .
       .
    
    int number;
    while (in.good())
    {
        in >> number;
        numbers.push_back(number);
    }
    but if there (in the file) is not end of file right after the last number, then the while loop will pass one more time and put one "extra" number to my vector -> which is bad.

    Does anybody know a solution to this problem?
    Petike

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So you (first) check whether the read is good, then you (second) do the read. C++ isn't psychic -- you have to read first, then check whether the read happened. Fortunately it's even easier done than said:
    Code:
    while (in >> number)

  3. #3
    Beginning game programmer Petike's Avatar
    Join Date
    Jan 2008
    Posts
    64

    Thumbs up

    Quote Originally Posted by tabstop View Post
    So you (first) check whether the read is good, then you (second) do the read. C++ isn't psychic -- you have to read first, then check whether the read happened. Fortunately it's even easier done than said:
    Code:
    while (in >> number)
    Thank you very much. It works!
    Petike

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  5. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM