Question on writing a simple program for class

I'm taking an introduction class in C++ and need a little help with an assignment. I need to write a simple program for the following:

Write a complete program that reads from a file. The file is called email.txt and can be found on the c drive under a folder called sentemails. The file can contain only a single entry about a sent email of the following format: email address, date sent, message. Display all three pieces of data to the user.

This is what I've written, but it does not show me the complete information from the file, which I made up and saved(which is just: email address, February 24, 2010, and some message content). I just get one word from the message content, but the email addy and date come up fine. Any help would be greatly appreciated!!!

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
ifstream inFile;

char email[30], month[8], message[81];
short day, year;

inFile.open("C:\\sentemails\\email.txt");

inFile >> email;
cout << email << "\n\n";
inFile >> month;
cout << month;
inFile >> day;
inFile.ignore(1, ',');
cout << " " << day;
inFile >> year;
cout << ", " << year << "\n\n";
inFile >> message;
cout << message << "\n\n";

system("PAUSE");
return EXIT_SUCCESS;
}
Last edited on
fstream::operator>>() stops reading at each [span of] whitespace. You could use getline and specify a delimiter (comma) to read the fields.

For example, here is a data file:
email address, 2/24/2010, and some message content


Try something like:
1
2
3
4
string email, date, message;
getline( inFile, email, ',' );
getline( inFile, date, ',' );
getline( inFile, message, ',' );


Note that you probably do not want a comma in the date. ;)


ADDENDUM:

Alternatively, if you place the email address and date each on their own line, you could use getline (without specifying a delimiter) to read them and loop to read the remaining (possibly multi-line) message content.
Last edited on
moorecm-

Thank you very much...works perfectly!
Glad to help out.
Topic archived. No new replies allowed.