Link to home
Start Free TrialLog in
Avatar of jewee
jewee

asked on

Format data from a file

In my code, I read data from a file..here are the first 2 lines...

990102
030901

I stored each line and what I want to do is put it in this format:
01/02/99
09/01/03

Basically, what I want to do is scan through the buffer (where I stored the line), and put them in that format.

How would I do this?
Avatar of skypalae
skypalae

Hi jewee,

char dd[3], mm[3], yy[3] ;

scanf ("%2s%2s%2s", yy, dd, mm) ;
printf ("%s/%s/%s", dd, mm, yy) ;

or sscanf() and sprintf() if you want to manipulate strings instead of input output.

S.
Avatar of jewee

ASKER

When I read in data to a file, that data is at the end, so I read it into a char buffer array.  Should I just set, for example, the first 2 bytes which is 99 into yy...etc??
Avatar of jewee

ASKER

or use a pointer and scan through the buffer?

sample code?
I don't understad what you really want to do now. Do you have a file containing lines "990102", "010901" etc., or you have some data and inside are these dates? Well, let's pass this and suppose that you have allready read a line that contains your date.

If you have a string containing "990102" in the middle it still depends whether the position is fixed or it is prefixed with a word (possibly "date:") or the position of the date is fixed (like 3rd word from beginning).

but if you know the exact position of the date in the string (lets say 'a') you can:
separate the date copying the substring out: strncpy (szDate, &szLine[a], 6) ;
and sscanf() it
or you can separate it using numbers
    int dd, mm, yy ;
    scanf ("%2d%2d%2d, &yy, &dd, &mm)

or you can get the numbers by your own:
    yy = (szLine[a]-'0')*10 + (szLine[a+1]-'0') ;
    dd = (szLine[a+2]-'0')*10 + (szLine[a+3]-'0') ;
    mm = (szLine[a+4]-'0')*10 + (szLine[a+5]-'0') ;

there are numerous approaches, you have to decide what to do according to your specific situation (for example if you want to calculate with the date further it would be better to get numbers instead of substrings).

S.
Avatar of jewee

ASKER

I know exactly where the string is within the line...this is how I extract it...

std::string last_field = line.substr(42);
Avatar of jewee

ASKER

I'm confused with how I use sscanf to separate it considering the location of the year, month and day needs to be changed to month, year, and day.
ASKER CERTIFIED SOLUTION
Avatar of skypalae
skypalae

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And don't get confused by scanf and printf. These are C (not C++) functions and if you don't understand them don't bother. You can learn C later.