Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>2 most important issues with you code:</p> <ul> <li>You SHALL check number of arguments BEFORE arguments check.</li> <li>Strings are compared using standard library functions like <code>strcmp()</code> or even better <code>strncmp()</code> if you know maximum length.</li> </ul> <p>Here is the <strong>C code</strong> that works. Hope this help.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main (int argc, char* argv[]) { if ((argc &gt; 1) &amp;&amp; ((strcmp(argv[1], "a") == 0))) { printf("hello world, argc: %d\n", argc); } else if ((argc &gt; 1) &amp;&amp; (strcmp(argv[1], "2") == 0)) { printf("hello everyone, argc: %d\n", argc); } for (int i = 0; i &lt; argc; i++) printf("%s\n", argv[i]); return 0; } </code></pre> <p>Some details aout string comparison. If you use <code>==</code> operator here (if you have not overloaded it) you just compare object addresses (look carefully, you have <code>char *</code> in both cases). Obviously your string literal and argument buffer have different addresses. You need to compare contents. Actually in C++ you can construct <code>std::string</code> and use comparison operator.</p> <p>So another, <strong>more C++ solution</strong> that works based on <code>==</code> operator:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string&gt; int main (int argc, char* argv[]) { if ((argc &gt; 1) &amp;&amp; (std::string(argv[1]) == "a")) { printf("hello world, argc: %d\n", argc); } else if ((argc &gt; 1) &amp;&amp; (std::string(argv[1]) == "2")) { printf("hello everyone, argc: %d\n", argc); } for (int i = 0; i &lt; argc; i++) printf("%s\n", argv[i]); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload