我想重新实现一个命令行(Bash),当我从STDIN中读取命令时,它只是一个简单的字符串,它不处理转义字符,例如,我想知道如何正确处理转义序列,即使它是一个十六进制或八进制。
echo "hello \x0A World"
output : hello \x0A World
echo "hello \t world"
output : hello \t world
所以我想知道如何正确处理转义符,即使是十六进制或八进制......谢谢。
逐个读取输入的字符。当你遇到一个 \
你对下一个字符进行切换(没有测试代码,抱歉)。
char s[10000]; //you can do the buffer checking yourself, this is off-topic now
int i = 0;
char c = getchar();
while (c != '\n')
{
if (c != '\\')
{
s[i++] = c;
c = getchar();
continue;
}
c = getchar();
switch (c)
{
case 'n':
s[i++] = '\n';
break;
case 't':
s[i++] = '\t';
break;
//do this for every character you want to escape
//for cases like 'x' and 'u', you will need to convert the next chunk of characters
// to a number (in the specific base) and set s[i++] to that value.
//if you encounter just digits (no letter), it's octal
}
c = getchar();
}