We'll use Ternary Operator, to check whether i
is the last character before '\0'
by checking s[i + 1] != 0
, here i
is the current index of the string. Here's a visual representation.
NOTE: Your variable char s[1001]
will be decayed to a pointer (exception: sizeof
operator).
Some improvements:
- Don't use
"%s"
, use "%<WIDTH>s"
, to avoid buffer-overflow
- Use
size_t
to iterate through an array.
- Instead of using bare
return 0;
, use return EXIT_SUCCESS;
, which is defined in the header file stdlib.h
.
- always check whether
scanf()
input was successful or not
Final Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char s[1001] = {0};
if (scanf("%1000s", s) != 1)
{
perror("bad input");
return EXIT_FAILURE;
}
for (size_t i = 0; s[i]; i++)
printf("%d%s", s[i], (s[i + 1]) ? "-" : "");
puts("\n");
return EXIT_SUCCESS;
}
Output:
Hello
72-101-108-108-111