-3

I am trying to input data from a text file: The line format is as follows... String|String|int double

Example: Bob|oranges|10 .89

I can get the line in as a string using Getline(infile, line)

I don't understand how to break the line into the distinct variables from the string variable.

Thanks

2 Answers2

1

for a start you could write some good old fashioned c code using strchr.

Or use string.find / find_first_of if you are using std::String

http://www.cplusplus.com/reference/string/string/find_first_of/

pm100
  • 48,078
  • 23
  • 82
  • 145
0

You marked this as C++. So perhaps you should try to use formatted extractors ...

Here is a 'ram' file (works just like a disk file)

std::stringstream ss("Bob|oranges|10 .89");
//               this ^^^^^^^^^^^^^^^^^^ puts one line in file

I would use getline for the two strings, with bar terminator

do {
   std::string cust;
   (void)std::getline(ss, cust, '|'); // read to 1st bar

   std::string fruit;
   (void)std::getline(ss, fruit, '|'); // read to 2nd bar

Then read the int and float directly:

   int count = 0;
   float cost;
   ss >> count >> cost;  // the space char is ignored by formatted extraction

   std::cout  << "\ncust: " << cust << "\n"
              << "      " << count << "  " << fruit
             << " at $"   << cost
             << " Totals: "  << (float(count) * cost)  << std::endl;

   if(ss.eof())  break;

}while(0);

If you are to handle more lines, you need to find the eoln, and repeat for every record of the above style.

This approach is extremely fragile (any change in format will force a change in your code).

This is just to get your started. It has been my experience that using std::string find and rfind is much less fragile.

Good luck.

2785528
  • 5,438
  • 2
  • 18
  • 20