I've seen a few different ways to convert a string to ascii and I was wondering what is the best way and why.
char str[100];
int i=0;
printf("Enter any string: ");
scanf("%s",str);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
-----------------------------------------------------------------------------
int main()
{
char *s="hello";
while(*s!='\0')
{
printf("%c --> %d\n",*s,*s);
s++;
}
return 0;
}
-----------------------------------------------------------------------------
char word[32];
int x = 0;
for ( x = 0; word[x] != '\0'; x++ )
{
}
-----------------------------------------------------------------------------
int main (void)
{
char string[50];
int i, sum;
scanf("%s", string);
sum = 0;
for(i = 0; i < strlen(string); i++)
sum += (int)string[i];
printf("(%d)\n", sum);
system("pause");
return 0;
}
-------------------------------------------------------------------------------
int num=0;
while (word[x] != '\0') // While the string isn't at the end...
{
num+=int(word[x])
x++;
}
I like the last while loop the most but I think I will use the last for loop. I will be reusing my array of char with fscanf %s multiple times. I think strlen can handle this better. Will the while loop get confused by multiple NULL characters or will fscanf be able to overwrite the NULL character each time. When I tested it with the last for loop it seemed to work correctly.