I need to parse a string into variables with varying data types (ints, strings).
The string in question was taken from a line in a file.
I'm wondering if there is a function similar to inFile >> var1 >> var2 >> etc; that I can use for a string. Below is the full line from the file.
2016/12/6 s "The incestuous relationship between government and big business thrives in the dark. ~Jack Anderson [4]" 0 3 39 blue white PATRICK BARDWELL pat.bardwell@bwpmlp.com
I have already assigned "2016/12/6," "s," and everything between the quotation marks to variables using inFile >> ;. Also, I took everything after the final occurrence of a double quote and stored that into the string restOfLine. Now, I'd like to parse restOfLine into variables for each value (0, 3, 39, blue, white, Patrick, Bardwell, pat.bardwell@bwpmlp.com should all be separate variables). Is there a method like inFile >> that I can use to do this? I also tried separating them with restOfline.find() and restOfLine.substr() but haven't been able to figure it out. Similarly, if I can separate each value from the entire line more efficiently than my current code, I'd prefer that. Current code below. Any help is much appreciated.
int main()
{
// Declare variables
string userFile;
string line;
string date;
char printMethod;
string message;
int numMedium;
int numLarge;
int numXL;
string shirtColor;
string inkColor;
string firstName;
string lastName;
string customerEmail;
string firstLine;
string restOfLine;
// Prompt user to 'upload' file
cout << "Please input the name of your file:\n";
cin >> userFile;
fstream inFile;
inFile.open(userFile.c_str());
// Check if file open successful -- if so, process
if (inFile.is_open())
{
getline(inFile, firstLine); // get column headings out of the way
cout << firstLine << endl << endl;
while(inFile.good())
// while we are not at the end of the file, process
{
getline(inFile, line);
inFile >> date >> printMethod; // assigns first two values of line to date and printMethod, respectively
int pos1 = line.find("\"");
// find first occurrence of a double quotation mark and assign position value to pos1
int pos2 = line.rfind("\"");
// find last occurrence of a double quotation mark and assign position value to pos2
string message = line.substr(pos1, (pos2 - pos1));
// sets message to string between quotation marks
string restOfLine = line.substr(pos2 + 2);
// restOfLine = everything after the message -- used to parse
}
inFile.close();
}
// If file open failure, output error message, exit with return 0;
else
{
cout << "Error opening file";
}
return 0;
}