There are safer and more robust ways to do what you are trying to do, but i assume this is a learning experience so try this:
#include <stdio.h>
# define MAX_CHARS 100
int main( void )
{
char str[MAX_CHARS];
int i; /* i should be an integer */
printf("Enter a string (less than %d characters) : ", MAX_CHARS );
/* scanf( "%s", str ); */ /* do not use &str, str is already a pointer */
fgets(str, MAX_CHARS - 1, stdin );
for ( i = 0; (i < MAX_CHARS) && ( str[i] != '\0' ); ++i ) ;
printf("Length of string: %d\n", i);
return 0;
}
using scanf("%s", str);
will only pick up the characters prior to a space,
so if your string is hello world
then the contents of str will only be hello
.
and if using scanf then if you enter more than MAX_CHARS, or in your case 100 characters, then you will have an overflow which is bad. Using fgets
is safer, but will include the \n
character in str.
normally you hit the enter
key to signal that is the end of input,
however you can hit control-d to signal end of file, and this will work with fgets
and the contents of str will not have the \n
character at the end. On my system I have to hit ctrl-d twice.