deepanshu
deepanshu

Reputation: 19

How do i convert a text file input to an array in c++

Hi I have a text file of the format phonenumber housenumber firstname lastname

I'm trying to read all the data ans store it in an array. I have used the code below. But it is reading only first line data. Can anyone help me why this is happening.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string.h>
#define Size 200

unsigned long long int mobilenumber[Size];
char seatnumber[Size][4];
char firstname[Size][30],lastname[Size][30];

using namespace std;
int main()
{
    //delcares the files needed for input and output//
    ifstream infile;
    ofstream outfile;

    infile.open("reservations.txt",ios::in);
    //opens files needed for output//
    outfile.open("pricing.txt");
    int i=0;
    if (infile.is_open())
    {
        infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
        i++;
        numberofbooking++;
    }
    infile.close();
    for(int i=0;i<=numberofbooking;i++)
    {
    cout<< mobilenumber[i]<<" "<< seatnumber[i]<<" "<< firstname[i]<<" "<< lastname[i];
    }
return 0;
}

Thanks in advance

Upvotes: 0

Views: 155

Answers (2)

dj1986
dj1986

Reputation: 362

Assuming you don't have data more than 200 in data file or your program will fail.

You are only reading once from the file so getting only first line data. You need to red from file till the EOF. add a while loop inside if(infile.is_open()){} . Read till EOF as below.

if (infile.is_open())
        {
            while (infile >> mobilenumber[i] >> seatnumber[i] >> firstname[i] >> lastname[i]) {
                cout << "Reading file" << endl;
                i++;
                numberofbooking++;
            }
        }

I don't see any benefit of i++ other than indexing. I think you can use numberofbooking for indexing as well.

Whenever you face such kind of issues, Try adding logs to check what is happening or use debugger. Hope this will help you.

Upvotes: 0

Object object
Object object

Reputation: 2054

The reason it is reading only one line of data is because that is all you have told it to do. Here:

...
 if (infile.is_open())
    {
        infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i];
        i++;
        numberofbooking++;
    }
...

This will run once, I think what you meant was a while loop:

while  (infile>> mobilenumber[i]>>seatnumber[i]>>firstname[i]>>lastname[i])
    {

        i++;
        numberofbooking++;
    }

This will do what you want, as long as 0 <= i <= 199, if i is outside that range then you will get undefined behaviour.

Upvotes: 1

Related Questions