dirk/C++/glibmm/strescape
Weingarten, 10-02-10
strescape – Quoting and Escaping
Quoting is a technique I favorize in text file management.
It grants that arbitrary text input (including control characters) can be excluded from special meanings independent of the syntax which is used otherwise.
C/C++ programmers know it from string literals, Unix users know the sophisticated (and sometimes headaching) shell quoting, and there are many other appearances in many other flavors.
Sometimes, it can be confusing to manage the quoting and unquoting leading to the appearance of undesired escape characters in visual output.
IMHO a well-balanced API and disciplined code design are the only solution.
So, this was something worth another sample.
Source Code
strescape.cc |
/** @file sample for Glib::strescape and Glib::strcompress
*
* Last CVS checkin:
* $Date: $
* $Author: scheff $
*/
/**************************************************************************/
// standard C/C++ header:
#include <iostream>
#include <string>
// Gnome header:
#include <glibmm/init.h>
#include <glibmm/stringutils.h>
/**************************************************************************/
using namespace std;
/** waits for user confirm.
*
* @param action text with next action
*/
static void pause(const char *action)
{
cout << "Press [ENTER] to " << action << ": " << flush;
string str; getline(cin, str);
}
/** provides the main function of application.
*
* @param argc number of command line arguments
* @param argv pointer to array of pointers to strings with command line
* arguments
* @return 0 ... application exited regularly\n
* else ... execution of application aborted
*/
int main(int argc, char *argv[])
{
Glib::init();
pause("start");
// samples
const char *samples[] = {
""
"Hello",
"Hi \"",
"\"quoted\"",
"\\\"quoted\\\""
};
int n = sizeof samples / sizeof samples[0];
// perform checks:
for (int i = 0; i < n; ++i) {
// perform a check
string sample = samples[i];
cout << "sample = '" << sample << '\'' << endl
<< "Glib::strcompress(sample) = '"
<< Glib::strcompress(sample) << '\'' << endl
<< "Glib::strescape(sample) = '"
<< Glib::strescape(sample) << '\'' << endl;
pause("continue");
}
// done
pause("finish");
return 0;
}
|
Output
| Console: |
|---|
Press [ENTER] to start: ↵
sample = 'Hello'
Glib::strcompress(sample) = 'Hello'
Glib::strescape(sample) = 'Hello'
Press [ENTER] to continue: ↵
sample = 'Hi "'
Glib::strcompress(sample) = 'Hi "'
Glib::strescape(sample) = 'Hi \"'
Press [ENTER] to continue: ↵
sample = '"quoted"'
Glib::strcompress(sample) = '"quoted"'
Glib::strescape(sample) = '\"quoted\"'
Press [ENTER] to continue: ↵
sample = '\"quoted\"'
Glib::strcompress(sample) = '"quoted"'
Glib::strescape(sample) = '\\\"quoted\\\"'
Press [ENTER] to continue: ↵
Press [ENTER] to finish: ↵
|
Files
Last modified: Sun Feb 21 18:48:39 2010