Using \n as a delimiter

Jun 7, 2012 at 10:32am
Hello.

My question is rather simple. While I can use strtok to, say, divide the contents of a string of months separated by spaces or commas into useful little bits, I'm a touch lost when I might be reading something from a file where said months are separated by the ends of lines instead of spaces or commas. What might be an easy way to do this?
I'm using fopen and then fgets to write into a string at the moment.


tl;dr:
strtok(string, "\n") does not work, what might I do?
Last edited on Jun 7, 2012 at 10:40am
Jun 7, 2012 at 1:14pm
istream::getline(char * s, streamsize n, char delim)
Jun 7, 2012 at 1:45pm
As the new line is a white space character you can use operator >> to read your data. For example,

char month1[10];
int month2;

std::cin >> month1 >> month2;
Last edited on Jun 7, 2012 at 1:45pm
Jun 7, 2012 at 2:00pm
On a file stream:
1
2
3
4
5
6
fstream fin( "input.txt" );
string line;
while( getline( fin, line ) ) {
    // process line
    cout << line << endl;
}


On a string stream:
1
2
3
4
5
6
stringstream sin( "1\n2\n3" );
string line;
while( getline( fin, line ) ) {
    // process line
    cout << line << endl;
}


(Untested examples, of course.)

References:
http://cplusplus.com/reference/string/getline/
http://cplusplus.com/reference/iostream/fstream/
http://cplusplus.com/reference/iostream/stringstream/
http://cplusplus.com/reference/iostream/
http://cplusplus.com/doc/tutorial/files/
Last edited on Jun 7, 2012 at 2:03pm
Jun 8, 2012 at 12:35pm
Oh, hey, wow, that's a lot of answers rather quickly, thanks guys. I rather like both using >> and the stream examples, though I've yet to get around to testing them.
Topic archived. No new replies allowed.