Problem reading from file

This is a discussion on Problem reading from file within the C++ Programming forums, part of the General Programming Boards category; I'm having trouble reading from a file with the following format: Code: John 51021400 Mary 51021411 Steve 51021406 Aaron 51021403 ...

  1. #1
    843
    843 is offline
    Registered User
    Join Date
    Oct 2010
    Posts
    135

    Problem reading from file

    I'm having trouble reading from a file with the following format:

    Code:
    John		51021400
    Mary		51021411
    Steve		51021406
    Aaron		51021403
    Kim		51021408
    For some reason the getline functions do not work. Here's the full code:

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    int main(void)
    {
        string name;
        string *id;
        string *num;
        int i, n = 0;
    
        ifstream fin("phone.txt");
    
        //get number of lines
        if (fin.is_open()) {
            while (fin.good()) {
                getline(fin,name);
                n++; //line counter up
            }
        }
    
        else { //file access verification
            cout << "File access error.";
            return 0;
        }
    
        //create dynamic array
        id = new string[n];
        num = new string[n];
    
        fin.seekg(ios::beg); //reset file position
    
        //assign names and numbers in file
        for (i=0; i<n; i++) {
            getline(fin, id[i], '\t');
            cout << id[i];
            while (fin.get() == '\t');
            fin.unget();
            getline(fin, num[i]);
            cout << num[i];
        }
    
        fin.close();
    
        return 0;
    }
    EDIT: Got it! I just had to clear the buffer halfway.
    Last edited by 843; 04-24-2011 at 12:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with reading of file
    By skumarisation in forum C++ Programming
    Replies: 3
    Last Post: 05-28-2010, 06:01 AM
  2. Problem of reading file!!
    By chintugavali in forum C++ Programming
    Replies: 3
    Last Post: 02-14-2008, 12:20 AM
  3. reading a file problem
    By 182 in forum C++ Programming
    Replies: 31
    Last Post: 02-13-2006, 05:59 PM
  4. problem with reading from a file
    By a1dutch in forum C Programming
    Replies: 14
    Last Post: 04-07-2005, 01:20 PM

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