c++ - 如何提供转义字符作为命令行参数

标签 c++ c

我想为我的 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/

相关文章:

c++ - 如何在 C++ 中通过引用传递堆栈矩阵

c - 为什么这个移植函数适用于二叉搜索树?

c++ - 在对象的指针 vector 上使用 STL 算法 (C++)

c++ - 当我在 Visual C++ 中 sleep (1000)时出错,使 srand()工作

c++ - 在 ubuntu 机器上构建 htdig

c++ - 通过预处理器创建 std::pair<std::string, some_enum>

c - C 中的 logsumexp 实现?

android - 如何将 utf8 转换为 iso-8859-7?

c - 对象宏的最大大小

c - 奇怪的 mmap 行为