hi
I am new student to C++ , I really need some help with this. Im trying to get an input from an External file ( Bike.txt ) Which has information about its price , Brand , displacement , power , and which category it goes into.
//Bike.txt
Ducati Monster //Name of the bike
10000 //Price of the Bike
Ducati //Brand of the bike
796 //Displacement of the bike
87 // BHP of the bike
700 // Category of the bike
#include<iostream>
#include<ifstream>
class Listing
{
int name;
int price;
char brand[30];
int displacement;
int power;
int category;
public : Listing()
{
price=0;
brand="\0";
displacement=0;
power=0;
category=0;
}
}
My Problem here is , I make an Object for Each bike , Then i read the information in the file to the object's data members , And please can someone Explain it to me how it is done or point me at the right direction.
bool Listing::Read (istream & is)
{ // Type of name must be string
if (! is.getline (name, "/"))
returnfalse; // read error
is >> price;
is.ignore (256,'\n'); // ignore any comments
// Continue for each reamining data element
returntrue;
}
A more elegant solution is to overload the >> operator:
what about the Integer numbers like Displace , Power , Price.
The question of how to read those depends on whether the comments you've shown in your example text file are present or not. If the comments are NOT present, then you can simply input each variable:
1 2 3 4 5
is >> price;
is >> brand; // Assumes never more than 1 word
is >> displacement;
is >> power;
is >> category;
However, if the comments ARE present, then you have to take steps to read line line and parse out the part up to the first /. The easiest way to do this is with stringstream. This assumes that a / won't occur in the data.
1 2 3 4 5
string line;
getline (is, line, '/'); // Read a line of text from the file
stringstream ss (line); // create a stringstream from the text line
ss >> price; // Input an integer from the stringstream
// Repeat for other data items
Can u explain why Bool is used here
The bool return value is used to indicate if a object was read successfully. Note that at line 4, false is returned if the getline failed. At line 8, if all items have been read successfully, true is returned. In the code I posted for the overloaded >> operator, the result of listing.Read() is not checked.
can u please explain the line for me.
Extracts characters from the input sequence and discards them, until either n characters have been extracted, or one compares equal to delim.