user3684811
user3684811

Reputation: 3

Cannot find the end of an array when opening a file

So I want to open a file and display the contents. Thing is, I don't know how many elements are used and how many elements are empty. So, when I try to display the elements the first few are shown but the rest are random numbers. How do I find and display the exact number of elements?

file:

10011   Ali         Doha        12355555    11-5-14     3434    7890 
10015   Ahmed       Al-Khor     51244444    13-6-14     3425    4455 
10014   Mohammed    Al-Wakra    53344333    17-7-14     5566    1234 
10012   Omar        Doha        56666666    10-8-14     1234    5678 
10013   Youssef     Al-Khor     7555512     5-5-14      88000   4532 
10019   Hamad       Al-Wakra    81234567    8-6-14      3125    1265     
10018   Jassim      Doha        86753541    9-7-14      9875    5566

code:

#include<iostream>
#include<fstream>
#include<string>

using namespace std;


int main()
{
    const int isize=10;
    ifstream datafile;
    datafile.open("D:\customers.txt");
    int customer_number[isize];
    string customer_name[isize]; 
    string customer_address[isize]; 
    long contact[isize]; 
    string Due_date[isize]; 
    int water_consumption[isize]; 
    int electricity_consumption[isize];
    double total_bill[isize];
    if (!datafile)//to know if the file is exist or not
         cout << "error" << endl;
    else
    {
        for(int i=0; i<1000; i++)
        {
            datafile >> customer_number[i];
            datafile>> customer_name[i];
            datafile>> customer_address[i];
            datafile>> contact[i];
            datafile>> Due_date[i];
            datafile>> water_consumption[i];
            datafile>> electricity_consumption[i];}
    }

        for(int i=0; i<isize; i++)
        {
              if(customer_number[i] == '\0')
                      break;
          else
                  cout << customer_number[i] << "\t" << customer_name[i] << "\t" << customer_address[i] << "\t" << contact[i] << "\t"
                      << Due_date[i] << "\t" << water_consumption[i] << "\t" << electricity_consumption[i] << "\t" <<  endl;

   }
      datafile.close();
     return 0;
 }

Upvotes: 0

Views: 55

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57698

Looks like each text line is a record, thus use std::getline with std::string to read a record.

When the number of records is unknown, you need a dynamic container, such as std::vector, std::list or std::map, not a fixed size array.

You will need to research the std::string methods and also std::istringstream for parsing the text line into native format fields. There are lots of examples on StackOverflow on how to do this.

So stop using fixed size arrays and use std::vector instead.

Upvotes: 1

Related Questions