LuckyMeadows
LuckyMeadows

Reputation: 17

Reading from File Containing Int and Char data types

I'm using Dev C++ for this programming assignment.

I'll try and give a basic rundown of the problem...

I'm trying to write a program that will read a time stamp and temperature reading from a file, then put the time stamp in a specific format and convert temperature to Celsius if needed. The input file has a sentinel number at the top of the file to tell how many lines of data need to be read. After this single int, each line then contains a number (ie. 200103121915 F51.13), there is a single space between the date and temp. The format is for YYYYMMDDHHMM. Without using pointers or any object oriented programming, we are supposed to convert each entry into a MM/DD/YYYY HHMM format and if the temperature is given in Fahrenheit, it needs to be converted to Celsius.

I'm running into problems with every approach I've tried. First, I was just going to read the entire 12 digit number as an int and then use some modulus commands to separate out each part. However, I found that int won't hold a number that large. Next, I thought to read each digit into an array and then piece together the individual arrays into the correct format. I don't know how to read in one digit at a time. I was thinking the array would need to be and int type, but then how would I deal with the F or C label? Basically I'm just looking for some basic ideas on how to accomplish this task, not asking for someone to write the code.

Upvotes: 0

Views: 732

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137810

If you're just getting started with I/O in C++, you might bookmark a reference site, because the library provides a lot of options and features.

  • cppreference.com is a non-authoritative but handy source, wiki-style.
  • Cay Horstmann wrote an article which covers more ground, and you can search for key words.
  • cplusplus.com has fairly good coverage of older language features, but has a few errors and isn't well updated.

As a further pointer, the std::setw manipulator might help to extract a given number of characters — although it won't stop numeric extraction from being too greedy.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283634

This would be MUCH easier just using the old-school stdio.h functions.

fscanf(stream, "%4d%2d%2d%2d%2d %c%f", &year, &month, &mday, &hour, &minute, &unit, &temp);

If you really really really can't use pointers, then

year = 1000 * (fgetc(stream) - '0');
year += 100 * (fgetc(stream) - '0');
year +=  10 * (fgetc(stream) - '0');
year +=       (fgetc(stream) - '0');
month =  10 * (fgetc(stream) - '0');
month+=       (fgetc(stream) - '0');

and so on...

Upvotes: 1

Related Questions