-1

I am new to C++ and I am trying to write a simple grocery shopping app, the input is in a format something like this:

Item Name
someid expiryDate manufacturerId cost

An example is:

Shampoo 8879 05 04 2015 1010 100.03

I want to format it in such a way that: 8879 05/04/2015 1000 $100.03 .....etc

How do I achieve this?

My attempt:

I tried using substring and then breaking the input down and then outputting in the required format but the issue i came across was that for example the price can be something like 45.00 then my approach would fail.

How can I achieve this?

Thank you

Mathew
  • 43
  • 5

1 Answers1

3

If you are reading from the console input you can use cin and istringstream:

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main()
{
    int id;
    int mm,dd,yy;
    int manufacturerId;
    double price;
    string priceString;
    char character; // used to read '/' and other symbols
    cin >> id >> mm >> character >> dd >> character >> yy >> manufacturerId;
    cin >> priceString;

    istringstream stream( priceString );
    stream >> character >> price;

    return 0;
}

Note: A nice approach if is to create your own struct/class for the complex objects (like date for example) to extract info and subclass operator>> for them.

struct date
{
    int month;
    int day;
    int year;
};

istream& operator>>(istream& stream,date& d)
{
    char character;
    stream >> d.month >> character >> d.day >> character >> d.year;

    return stream;
}

Then you can use

date d;
cin >> d

to read dates which is much more concise and keeps the code in main simple.

GeneralFailure
  • 1,085
  • 3
  • 16
  • 32
  • Thanks for your solution, but my question is little different. In the sense my input format is like: 8879 05 04 2015 1010 100.03. I basically want to take this input and then store them in variables like month, date, year, id, price, etc. Probably using a for loop. How do i achieve this? – Mathew Oct 12 '15 at 19:54
  • 1
    Well in the code i have some variables( id, mm, dd, yy, price ) to hold this information and populate them when reading from input stream. If you run the code and paste 8879 05 04 2015 1010 $100.03 in the console you will have the data extracted in those variables. – GeneralFailure Oct 12 '15 at 19:57