yiwll
yiwll

Reputation: 65

Trying to convert elements of a string into numbers based on position of character in alphabet

I'm trying to take the string char theString[256] = "BreakfastLunchDinner"; and covert each character into a number based on its position in the alphabet, i.e. B = 2, f = 6, l = 12, etc.

Here is my code so far:

void main()
{
    char theString[256] = "BreakfastLunchDinner";
}

void firstLast(char theString[], char *first, char *last)
{
    int i = 0;
    int num[256];

    while(theString != '\0')
    {
            if(theString[i] >= 'A' && theString[i] <= 'Z')
            {
            num[i] = theString[i] - 'A';
            }
            else if(theString[i] >= 'a' && theString[i] <= 'z')
            {
            num[i] = theString[i] - 'a';
            }
            i++;
    }
}

I've included the declaration in the main function to try and be as detailed as possible, the pointers are for later use, and I'm currently focusing on the conversion aspect explained above. When I try to run the "firstLast" function in a separate program on its own I get segmentation fault core dumped from the compiler. Any help is greatly appreciated, thank you.

Upvotes: 1

Views: 123

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

As theString never changes, the loop will never terminate, and theString[i] probably ventured off somewhere it isn't supposed to go, resulting in the segfault.

Your test should be theString[i] != '\0'.

Upvotes: 5

Related Questions