So, i want to make a program in c where you input a string then the output will be ascii number of every character in that string split by '-'. i almost done then i dont know how to remove the last '-' in the output of my code. exp. input: abc output: 97-98-99. Here is my code :
char s[1001];
scanf("%s",&s);
for(int i=0;s[i]!='\0';i ){
printf("%d-",s[i]);
}
return 0;
}
My output : 97-98-99-
CodePudding user response:
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;
, usereturn EXIT_SUCCESS;
, which is defined in the header filestdlib.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("00s", 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
CodePudding user response:
Slightly rearrange your logic:
for(int i=0;s[i]!='\0';i ){
if( i != 0 )
printf("-");
printf("%d",s[i]);
}
CodePudding user response:
check if current index is not the last index then print -
otherwise it's the last index and print newline
char s[1001];
scanf("%s",&s);
int len = 0;
for(;s[len]!='\0';len );
for(int i=0;i<len;i ){
printf("%d",s[i]);
if(i 1 != len)
printf("-")
else
printf("\n")
}
CodePudding user response:
Instead of using strlen()
, length or repeated tests in a loop, simply change the separator.
const char *separator = "";
for (size_t i=0; s[i]!='\0'; i ) {
printf("%s%d",separator, s[i]);
separator = "-";
}