argv[]
is the array that holds your command line parameters, argv[1]
is the first one (other than the command representation itself in argv[0]
, of course). You assign it to s
then immediately overwrite s
, so it's not really needed here.
The reason you're having to enter two lines is the \n
at the end of your input format. It requires whatever can match the format string followed by a newline, hence the %s\n
is eating your first newline so that scanf
has to go back for another one.
%s
on it's own will fix that problem but introduce another one if what you're after is a full line of input - it will only read up to the first whitespace. For a proper line input function, see here.
It does full line input with protection against buffer overflows and detection/cleanup of lines that were too long, something sorely missing in the scanf("%s")
input method.
In addition, the if
statement within the while
is superfluous here since the while
itself will catch the end of the string, and it makes little sense to have both input
and s
refer to the same array (it would make sense if you changed s
at some point, but that's not happening here).
So, a variant without the advanced line iput function could be as simple as:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char* argv[]) {
char input[256];
int str_length = 0;
printf ("Please enter a string: ");
scanf ("%s", input);
while (input[str_length] != '\0') /* Or consider using strlen() */
str_length++;
printf ("%d\n", str_length);
return 0;
}
If you enter Hello
, you'll see that it prints out 5
immediately. You'll also see 5
if you enter Hello Pax
, which is one reason to choose the advanced input function (the other, very important, reason is to avoid introducing a buffer overflow vulnerability into your program).