0

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.

2
Contributors
1
Reply
26
Views
3 Years
Discussion Span
Last Post by Ancient Dragon
0

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).

Edited by Ancient Dragon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.