我想为我的 C 程序提供转义字符作为命令行参数:
#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;
}
运行时它给出:
/a.out "\t"
str1: :
str2:\t:
所以看起来我的 \t
被解释为斜杠 t 而不是制表符
是否有一个简单的解决方案,或者我是否必须检查我希望程序处理的每个转义字符?像这样的吗?:
char *truetab="\t";
if(argv[1][0]=='\\' && argv[1][1]=='t')
res = truetab;
谢谢。
最佳答案
不幸的是,您需要手动执行此操作:处理转义序列是编译器的工作,当 "hello\tworld"
常量最终出现在编译代码中的字符串常量区域时, \t
已被 ASCII 代码 9 (TAB
) 替换。应该没那么难 - 事实上,这是经典 K&R 的练习编号 3.2书:
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.
关于c++ - 如何提供转义字符作为命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9536222/