-
getline() help!
Hi all,
I have the following lines in a file:
------------------------------------------------------
88 co-processeur math D33 87.00 34
804 co-processeur math D40 110.00 28
845 disque dur 40 Mb 28 ms 169.00 31
850 disque dur 120 Mb 15 ms 289.00 47
920 disque dur 340 Mg 13 ms 768.00 17
-------------------------------------------------------
Each line holds 4 values: id, productName, price, quantity
I can't use strtok() because the productName contains spaces and I can't tokenize on spaces. Also, there could be one or more spaces between the productName and the price.
I can't think of a way to parse the line, please help me if you can. thanks.
-
Well, a simple way to solve your problem is to use another field separator (for example the pipe (|))
------------------------------------------------------
88|co-processeur math D33|87.00|34
804|co-processeur math D40|110.00|28
845|disque dur 40 Mb 28 ms|169.00|31
850|disque dur 120 Mb 15 ms|289.00|47
920|disque dur 340 Mg 13 ms|768.00|17
-------------------------------------------------------
The hard way to do this is by starting at the end of the line and read the quantity and price first (use strrchr for example):
Code:
#include <iostream.h>
#include <fstream.h>
#include <string.h>
void main()
{
char buffer[1024];
ifstream file("C:\\temp\\products.txt");
if(!file)
{
cout << "Unable to open file" << endl;
}
else
{
while(file.good())
{
// remove spaces at end of line
while(buffer[strlen(buffer)-1] == ' ')
buffer[strlen(buffer)-1] = 0;
// find last space in line
char *quantity = strrchr(buffer, ' ');
// put null character in stead of space and increase pointer
*quantity++ = 0;
// find last space in line
char *price = strrchr(buffer, ' ');
*price++ = 0;
// find FIRST (strchr) space in line
char *desc = strchr(buffer, ' ');
*desc++ = 0;
cout << "ID = " << buffer << endl;
cout << "Description = " << desc << endl;
cout << "Price = " << price << endl;
cout << "Quantity = " << quantity << endl;
}
}
}