Reputation: 6948
I want to supply escape characters for my C program as command line arguments:
#include <cstring>
#include <cstdio>
int main(int argc,char**argv){
const char *str1 = "\t";
const char *str2 = argv[1];
fprintf(stderr,"str1:%s:\nstr2:%s:\n",str1,str2);
return 0;
}
When running this it gives:
/a.out "\t"
str1: :
str2:\t:
So it looks like my \t
is being interpreted as slash t instead of tab
Is there an easy solution for this, or do I have to check for every escape charechter I want my program to handle? Something like this?:
char *truetab="\t";
if(argv[1][0]=='\\' && argv[1][1]=='t')
res = truetab;
Thanks.
Upvotes: 2
Views: 3174
Reputation: 11
If you are using bash in linux, you can press Ctrl+V and hit tab, and quote it with ''
, you can pass almost any escape character like esc
type this:
./a.out 'Ctrl+v tab'
BTW, I don't know which software provides this functionality, maybe all unix-like terminal can do it
Upvotes: 1
Reputation: 726489
Unfortunately, you need to do it manually: processing escape sequences is compiler's job, by the time the "hello\tworld"
constant ends up in the area of string constants in the compiled code, the \t
is already replaced by the ASCII code 9 (TAB
). It should not be that difficult - in fact, it's an exercise number 3.2 of the classic K&R book:
Exercise 3-2. Write a function escape(s,t) that converts characters like newline and tab into visible escape sequences like \n and \t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters.
Upvotes: 1