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.

Will the while loop get confused by multiple NULL characters

No, it will stop when it encounters the first NULL character, all others are ignored.

will fscanf be able to overwrite the NULL character each time

Maybe, it will try to store as many characters as it can in the buffer until it either encounters '\n' in the file, end-of-file, or fills up the buffer.

Why do you want the sum of all characters in the file? That may not work if the sum exceeds the max value that can be stored in num (see the max value in limits.h standard header file).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.