Text auslesen
-
Moin zusammen,
ich wollte ein kleines Programm schreiben welches mir einen bestimmten Text aus einem Textfile ausliesst. Es geht um folgendes:
Die auszulesende Datei ist in etwa so aufgebaut -->
<tag>TEXT</tag>Nun will ich ein C/C++ Programm schreiben welches mir den Text einliesst und danach nach <tag>TEXT</tag> sucht und den TEXT herausliesst und separat abspeichern kann.
Mgölicherweise hat hier jemand ne Idee dazu.
Vielen Dank im voraus
-
schau dir mal xml an. Sie eigentlich das gleiche, gibt dafür sehr viele Beispiele.
mfg liggi
-
Eine quick and dirty lösung
#include <iostream> #include <string> #include <list> int main() { std::string input = "<tag>TEXT</tag>"; std::string startTag, endTag, value; unsigned int i = 0; while (input[i] == ' ' || input[i] == '\n' || input[i] == '\t') { ++i; if (input.length() <= i) { break; } } if (input[i] == '<') { ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } while (input[i] != '>') { startTag += input[i]; ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } } ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } while (input[i] != '<') { value += input[i]; ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } } ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } if (input[i] != '/') { std::cerr << "Error: expected '/'" << std::endl; } ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } while (input[i] != '>') { endTag += input[i]; ++i; if (input.length() <= i) { std::cerr << "Error: unexpected end" << std::endl; return 1; } } } if (startTag != endTag) { std::cerr << "Error: " << startTag << " != " << endTag << std::endl; return 1; } std::cout << "'" << startTag << "' = '" << value << "'" << std::endl; return 0; }