简体   繁体   English

以下C程序的输出将如何?

[英]What will be the output of following C program and how?

What wil be the output? 输出是什么? I am confused of the \\\\ . 我对\\\\感到困惑。 How does it work? 它是如何工作的?

#include <stdio.h>
void main(){
    printf("\\nab");
    printf("\\bsi");
    printf("\\rha");
}

The output will be \\nag\\bsi\\rha . 输出将是\\nag\\bsi\\rha The string "\\\\" converts to literal "\\" . 字符串"\\\\"转换为文字"\\"

That is because \\n symbolizes a new line, and there are several other uses for the single char \\ . 这是因为\\n换行,并且单个char \\还有其他用途。 If it didn't work this way, there would be no way to print the literal \\n . 如果这种方式行不通,将无法打印文字\\n

The answer will be: 答案将是:

\nab\bsi\rha

1 - The three text are printed together because you are using printf without an escape character \\n , if you instead use 1-三个文本一起打印,因为您正在使用不带转义符\\n printf ,如果您改为使用

...
printf("\\nab\n");
printf("\\bsi\n");
printf("\\rha\n");
...

You will get 你会得到

\nab
\bsi
\rha

In the first print you are writing \\n and this means a new line, but you are declaring two slashes that indicate to print 'as is' a single slash (in C to print a slash you must be use \\\\ (two) because a single slash is pretended to use for special escape characters like \\n). 在第一个打印中,您正在编写\\n ,这表示换行,但是您声明了两个斜杠,这些斜杠表示要按原样打印单个斜杠(在C中要打印斜杠,必须使用\\\\(两个),因为假装单个斜杠用于特殊转义字符,例如\\ n)。

Try to execute the your original with it to see the main difference: 尝试用它执行原始文件,以了解主要区别:

#include <stdio.h>

void main()
{
  printf("\nab\n");     /* Note that I am using a escape character \n to make a new line after each print */
  printf("\bsi\n");
  printf("\rha\n");
}

Basically, If this \\ is used before special characters, it is called an escape literal. 基本上,如果在特殊字符之前使用此\\ ,则称为转义文字。 What this does is, remove the functionality of special characters right infront of it. 这是在其前面删除特殊字符的功能。 Ex: Incase you want to print this line in output : Hi this, ", is a quote symbol . You would write it as : printf("Hi this, \\", is a quote"); 例如:如果要在输出中打印此行: Hi this, ", is a quote symbol 。您可以将其写为: printf("Hi this, \\", is a quote");

Similarly for escape sequences such as \\n \\t \\b, to remove the special characte \\ from it would require an escape literal. 同样,对于转义序列,例如\\ n \\ t \\ b,要从中删除特殊字符\\则需要转义文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM