Home > Blockchain >  Why the output not show up according to my txt file?
Why the output not show up according to my txt file?

Time:07-09

Why can't I retrieve all of the data from a txt file using c ?

This is the data in the txt file:

Standard    ;40 90 120
Delux       ;70 150 200
VIP         ;110 200 300

This is my coding:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <bits/stdc  .h>
#include <vector>
using namespace std;

struct Room
{
   string roomType;
   float tripleBed;
   float doubleBed;
   float singleBed;
};

void displayRoom(Room []);
void inputRoom(ifstream &, Room []);

int main()
{
   Room choice[3];

   ifstream room("Room.txt");
   if(room.fail())
   {
       cout<<"File does not exist\n";
       cout<<"Press any key to exit the program\n";
       return -1;
   }

   inputRoom(room, choice); 
   displayRoom(choice);
   room.close();
    
   return 0;
}

void displayRoom(Room choice[])
{
    cout<<"\n\n************** ROOMS SECTION ***************\n"<<endl;
    cout<<"ROOM TYPE"<<"\t"<<"TRIPLE BEDDED"<<"\t"<<"DOUBLE BEDDED"<<"\t"<<"SINGLE BEDDED"<<endl;

   for(int i=0; i<3; i  )
   {
        cout<<choice[i].roomType;
        cout<<"RM"<<choice[i].tripleBed<<"\t\tRM"<<choice[i].doubleBed<<"\t\tRM"<<choice[i].singleBed<<endl;
   }
 }

void inputRoom(ifstream &room, Room choice[])
{
    string tokens[4];
    string line;
    int j = 0;
 
    while (room.good())
    {
        int i = 0;
        getline(room, line); 
        stringstream ss (line); 
        string temp; 
     
        while (getline (ss, temp, ';'))
        { 
            tokens[i] = temp; 
            i  ; 
        }
    
        choice[j].roomType = tokens[0];
        choice[j].tripleBed = atof(tokens[1].c_str()); 
        choice[j].doubleBed = atof(tokens[2].c_str());
        choice[j].singleBed = atof(tokens[3].c_str());
        j  ;
    }
}

This is the output

************** ROOMS SECTION ***************

ROOM TYPE       TRIPLE BEDDED   DOUBLE BEDDED   SINGLE BEDDED
Standard        RM40            RM0             RM0
Delux           RM70            RM0             RM0
VIP             RM110           RM0             RM0

--------------------------------
Process exited with return value 0
Press any key to continue . . .

As you can see, at double bedded and single bedded column should have a value that has been defined by me but why the value of the columns zero? can someone help me? Thank you in advance for helping me.

CodePudding user response:

Look at your input loop

    while (getline (ss, temp, ';'))
    { 
        tokens[i] = temp; 
        i  ; 
    }

that reads tokens separated by semicolons.

Look at you actual input

Standard    ;40 90 120

Only the first and second token are separated by a semicolon. The rest are separated by spaces.

The simple thing to do would be to edit your data so that it matches your code. E.g.

Standard;40;90;120
  •  Tags:  
  • c
  • Related