transforming "\n\t\r" to binary

Started by
14 comments, last by deffer 18 years, 10 months ago
Hi. So this is about formatting output like printf does, but the task is easier. To change '\n' into 0x0A and \t \r the same way. Leaving %d and so intact, so I can't just use sprintf :( How this can be done, from stl string to stl string? Cheers. /def
Advertisement
Okay, not sure what you mean, but try this.

printf( "%02x %02x %02x", (unsigned int)'\n', (unsigned int)'\t', (unsigned int)'\r');
william bubel
Why don't you just manually convert it, using the ASCII table?

ace
If you mean you have "\n" as two chars ansd you want to convert it to a sinlge char '\n' then you need to parse your string.

If you mean you have the single char '\n' than that already == 0x0A.

If you have the char '\n'and you want to print 0x0A then there is a std stream manipulator that takes int types and outputs hex.

It would be helpful if you told us exactly what it is you are trying to do.
Wow, I really messed up the explanation. ;Sorry.

Quote:Original post by Nitage
If you mean you have "\n" as two chars ansd you want to convert it to a sinlge char '\n' then you need to parse your string.


This is exactly what I mean.
But I wouldn't want to parse it by hand.
If I launch: printf("\n"), it will output one byte: 0x0A. It's simple.
So maybe there's a quicker way?

Cheers.
/def
Ok.
Guess there's no choice, so I wrote it by hand :(

string reformatString(const string &str){	int len = (int)str.length();	if (len <= 1)		return str;	const char* pBuf = str.c_str();	string strOut = "";	int i;	for (i=0; i<len-1; )	{		char c = pBuf[i++];		if (c == '\\') {			char c = pBuf[i++];			if (c=='n') {				strOut += '\n';			} else if (c=='t') {				strOut += '\t';			} else if (c=='\\') {				strOut += '\\';			} else if (c=='r') {				// skip			} else {				strOut += '\\';				strOut += c;			};		} else {			strOut += c;		};	};	if (i < len) {		strOut += pBuf;	};	return strOut;};


Cheers.
/def
Quote:Original post by deffer
If I launch: printf("\n"), it will output one byte: 0x0A. It's simple.
So maybe there's a quicker way?

The \n is translated at compile time.
Free Mac Mini (I know, I'm a tool)
...Yes, he's trying to do the same thing as a compiler when he recieves a string with "\n" (ie: "\\n") in his program (ie: convert it to a single newline charcter).
Quote:Original post by igni ferroque
The \n is translated at compile time.


The case is:
I'm writing a compiler, so as you just said: it has to be performed by me.

Cheers.
/def
Quote:Original post by deffer
Guess there's no choice, so I wrote it by hand :(

[censored evilness]



sorry but that code looks horrid [grin][lol], std::basic_string::find_first/last(_not)_of are your friends, found out more here or wait until i get some sleep and i'll show you something [wink].

This topic is closed to new replies.

Advertisement