I have a structure with an int and two strings. When reading in the file it is comma seperated for the first two values and the last value is terminated by a newline. The third argument could be empty however.
ex data: 7, john doe, 123-456-7891 123 fake st.
I want to make it so that my program will grab the first number and put it in the int, find the comma and put the second number in the struct's string etc.
First question is should I use a class instead? I have seen the getline(stream, myString, ',');
but my arguments are different data types so I can't just throw them all into a vector.
my code:
struct Person{
int id;//dont care if this is unique
string name;
string extraInfo;
};
int main(int argc, char* argv[]){
assert( argc ==2 && "Invalid number of command line arguments");
ifstream inputFile (argv[1]);
assert( inputFile.is_open() && "Unable to open file");
}
What is the best way of storing this information and retrieving it from a file that is comma separated for the first two and ends with a newline? I also want the program to ignore blank lines in the file.
You can still use the
getline
approach for tokenising a line, but you first have to read the line:I'd read the file line-by-line using normal
getline()
. Then, put it into astringstream
for further parsing or usestring
'sfind()
functions to split the text manually.Some more notes:
Person
, then the answer is that it doesn't matter."a,b"
to not be split by the comma. Make sure you have tests that assert the required functionality.Once you get the line in string using getline, use strtok.
You'll need to include
#include <string.h>
to use strtok