One issue!

据说在学习一门语言的时候输出Hello World!会带来好运。

哪怎么输出Hello World呢?难道就是像下面这样:

1
2
3
4
5
6
#include<stdio.h>
int main()
{
printf("Hello World!");
return 0;
}

是的,我们就是要输出上述源代码。

输出源码

如果我们直接运行

1
2
3
4
5
6
7
8
9
10
int main()
{
printf("#include<stdio.h>
int main()
{
printf("Hello World!");
return 0;
}");
return 0;
}

不出意外地报错,由于各种语言存在保留字以及需要使用无法输入的字符,因此需要对部分地方进行转义。
修改后的源码如下:

1
2
3
4
5
int main()
{
printf("#include <stdio.h>\nint main()\n{\nprintf(\"Hello world\\n\");\nreturn 0;\n}");
return 0;
}

此处,我们对换行符通过\n进行了转义,还对”以及\进行了转义。

AWSL


阿伟死了!这道题与上述问题相似,不过又有一个坑。

我最开始的源码是这样的:

1
2
3
4
5
int main()
{
printf("#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n\t//输出 Hello World !\n\tcout<<\"Hello World !\"<<endl;\n\n\treturn 0;\n}");
return 0;
}

我使用了\n和\t来对上述源码进行转义,提交之后报格式错误。由于有了前几题的心酸历程,我去仔细看了下格式,发现缩进只有四个空格。而我使用Mingw-W64编译出来的代码中制表符占据了八个空格的位置,不同编译器以及编辑器的差异造成了上述问题。

修改后的源码如下:

1
2
3
4
5
int main()
{
printf("#include <bits/stdc++.h>\nusing namespace std;\n\nint main()\n{\n //输出 Hello World !\n cout<<\"Hello World !\"<<endl;\n\n return 0;\n}");
return 0;
}

在使用Tab还是Space的问题上的讨论似乎成为了与Vim/Emacs哪个更好相似的问题。

转义表

以下即为C语言常用转义字符表格:

转义字符 意义 ASCII码值(十进制)
\a 响铃(BEL) 007
\b 退格(BS) ,将当前位置移到前一列 008
\f 换页(FF),将当前位置移到下页开头 012
\n 换行(LF) ,将当前位置移到下一行开头 010
\r 回车(CR) ,将当前位置移到本行开头 013
\t 水平制表(HT) 009
\v 垂直制表(VT) 011
\’ 单引号 039
\” 双引号 034
\\ 反斜杠 092

当然C语言也提供一种数字转义方法,如下:

八进制转义 十六进制转义 名称/意义
\7 \x07 响铃
\10 \x08 退格
\12 \x0A 换行
\14 \x0C 换页
\40 \x20 空格
\60 \x30 0
\101 \x41 A
\141 x61 a