For the given arguments, I need to retrieve its corresponding values (only the last 2 columns)
My idea: (kindly correct me if I am wrong)
open a file,
read a line,
Store them in a class (which has 6 members: itemname,id,code,wt,discount,coupon)
use method to extract 3 letters of itemname and compare it with user argument1 and repeat the same for user argument2.
If matches, fetch its discount and coupon values.
My doubt: I am not sure how to spilt the values from a line and store in class
Here is what I have done.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class temp
{
string itemName;
int itemId;
int itemCode;
int itemWt;
float coupon;
float discount;
}
int main () {
string line;
ifstream myfile ("item.txt");
// string text ="AL"; // search pattern
temp tempObj;
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
// line.find(text);
cout<<line;
}
myfile.close();
}
else cout << "Unable to open file";
system("pause");
return 0;
}
nah... try one of the string functions... like find , get the position, read out everything that follows and convert it to the format of your desire:)... check the reference http://cplusplus.com/reference/string/string/find/
Since your file consists of only 20 entries, linear searching (i.e. checking every entry in the file for a match) is a good approach. Get itemname in a string using operator >> with your ifstream object. Then check if it matches the args given by the user. If not, use the ignore function of your ifstream object to get rid of the rest of the line and move on to the next. If you have a match then simply use operator >> to get the rest of the data into your variables.
str userArg1 = "XYZ";
str userArg2 = "Efg";
// i use getline to read each line from the file.
itemXYZ = line.substr(0,userArg1.length()); // gave me XYZ
itemEfg = line.substr(6,userArg2.length()); // gave me Efg
if((userArg1==itemXYZ )&&(userArg2==itemEfg))
{
//print rec.discount , rec.coupon
//I need to send these 2 arguments to another function
myfile.close();
}
Also got an error saying out of range exception for substr.
I tried changing the starting position, but it still throws me that error.
I got another idea, was not sure how to implement it...
// convert string to string array
Eg. string line = "XYZ123Efg 234 232 171 -21 -3332324234"
string strArray[0] ="XYZ123Efg "
string strArray[1] = "234"