0

I'm trying to do something like

strcmp(argv[3], "stdout")

however, in the command line I don't want to type

stdout\0

what's the best way to get rid of the \0 at the end of a string literal?

Thanks!

update:

Thanks guys. I found what's wrong with my code... I should have used

strcmp(argv[3], "stdout") == 0

Thanks @Nicol Bolas

4

3 回答 3

3

You don't have to type "stdout\0" on the command line. Whichever way your system makes command-line arguments available to your process (it differs by operating system) automatically adds the null character.

As you know, a C-style string is terminated by the null character, which is written in code as '\0'. If that character weren't at the end of the string, a function such as strcmp would keep going well beyond the end of the string, since such a string flouts convention. Since the terminating null character is the C convention, however, the compiler is smart enough to add the null character to the end of a string literal, and the system is smart enough to add the null character to the command-line arguments stored in the memory of a freshly created process. If argc is greater than 3, and the third argument you type on the command-line for your program is "stdout", the call to strcmp(argv[3], "stdout") will return 0 to mean that the two strings match.

于 2013-02-03T03:32:42.557 回答
2

You don't need to type \0 in most cases. String literals have a \0 implicitly appended to them, and the C functions that store string data into character arrays will append a \0 on the end (which is why the documentation for many of those functions specifies that your character buffer must have enough space for the string and the null terminator).

于 2013-02-03T03:33:07.667 回答
2

字符串字面量由源字符集中的零个或多个字符组成,并用双引号 (") 括起来。字符串字面量表示一系列字符,它们一起形成一个以空字符结尾的字符串。

strcmp 开始比较每个字符串的第一个字符。如果它们彼此相等,则继续以下对,直到字符不同或到达终止空字符。

所以你不需要写\0在最后stdout,你需要比较to的返回strcmp0

if (strcmp(argv[3], "stdout") == 0)
于 2013-02-03T03:38:20.667 回答