Thread: Problem reading from file

  1. #1
    Registered User
    Join Date
    Oct 2010

    Problem reading from file

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

    John		51021400
    Mary		51021411
    Steve		51021406
    Aaron		51021403
    Kim		51021408
    For some reason the getline functions do not work. Here's the full 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()) {
                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');
            getline(fin, num[i]);
            cout << num[i];
        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, 01:20 AM
  3. reading a file problem
    By 182 in forum C++ Programming
    Replies: 31
    Last Post: 02-13-2006, 06: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