multiparser.cpp added by _1126 on Mon Dec 10 14:23:03 2012
#include <iostream> #include <fstream> #include <cstring> void readAndPrintXML(std::ifstream *input); void readAndPrintPeople(std::ifstream *input); int main(int argc, char * argv[]) { char character; if (argc != 2) std::cout << "usage: " << argv[0] << " <file-to-parse>." << std::endl; else { std::ifstream input; input.open(argv[1]); if (!input.is_open()) std::cout << "Error: could not open the file." << std::endl; else { input.get(character); if (character == '<') { input.putback(character); readAndPrintXML(&input); } else if (character == 'N') { input.putback(character); readAndPrintPeople(&input); } else std::cout << "Wrong input." << std::endl; } input.close(); } return 0; } void readAndPrintXML(std::ifstream *input) { char character; char buffer[100]; int i; enum position { inbetween, inName, expAttName, expAttValue, inAttValue }; enum position position; while (!input->eof()) { input->get(character); switch(character) { case '<': position = inName; i = 0; break; case ' ': if (position == inName) { buffer[i] = '\0'; std::cout << "Name of Tag: \t\t" << buffer << std::endl; i = 0; position = expAttName; } break; case '=': if (position == expAttName) { buffer[i] = '\0'; std::cout << "Name of Attribute: \t" << buffer << std::endl; i = 0; position = expAttValue; } break; case '"': if (position == expAttValue) { position = inAttValue; i = 0; } else if (position == inAttValue) { buffer[i] = '\0'; std::cout << "Value of Attribute: \t" << buffer << std::endl; i = 0; position = expAttName; } break; default: if (position != inbetween) { buffer[i] = character; i++; } } } } void readAndPrintPeople(std::ifstream *input) { char character; char buffer[100]; int i; enum position { inbetween, inLastName, expFirstName, inFirstName, expBirthdate, inBirthdate }; enum position position; while (!input->eof()) { input->get(character); switch (character) { case ':': if (position == inbetween) position = inLastName; else if (position == expBirthdate) position = inBirthdate; i = 0; break; case ',': if (position == inLastName) { buffer[i] = '\0'; std::cout << "Last Name: " << buffer << std::endl; i = 0; position = expFirstName; } if (position == expFirstName) position = inFirstName; break; case ' ': if (position == inbetween) i = 0; else if (position == expFirstName) i = 0; break; case '.': if (position == inFirstName) { buffer[i] = '\0'; std::cout << "First Name: " << buffer << std::endl; i = 0; position = expBirthdate; } else if (position == inBirthdate) { buffer[i] = character; i++; } break; case '\n': if (position == inBirthdate) { buffer[i] = '\0'; std::cout << "Birthdate: " << buffer << std::endl; i = 0; position = inbetween; } break; default: if (position != inbetween) { buffer[i] = character; i++; } } } }