Read numbers from file to std::vector

This is a discussion on Read numbers from file to std::vector within the C++ Programming forums, part of the General Programming Boards category; Hello, how to read all numbers from a file to std::vector? I have tried this one: Code: ifstream in; 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,185
    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, 11:04 AM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 05:27 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 04:44 PM
  4. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 02:19 PM
  5. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 01:13 AM

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