Reputation: 7491
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
Upvotes: 0
Views: 307
Reputation: 45410
A string literal consists of zero or more characters from the source character set surrounded by double quotation marks ("). A string literal represents a sequence of characters that, taken together, form a null-terminated string.
strcmp starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
so you don' t need to write \0
in the end of stdout
, you need to compare the return value of strcmp
to 0
:
if (strcmp(argv[3], "stdout") == 0)
Upvotes: 2
Reputation: 46193
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).
Upvotes: 2
Reputation: 14458
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.
Upvotes: 3