Computer Science Canada

Strings

Author:  dchini [ Fri Oct 03, 2008 11:43 am ]
Post subject:  Strings

Hey I'm trying to manipulate the array of chars, dan, to an output of my choice. Any help or advice would be much appreciated!

NOTE: Dan starts at index [0]
Ran starts at index [17]
12 starts at index [34]
there is spaces inbetween


c:

#include <stdio.h>

int main(int argc, char *argv[])
{
char dan[]= "Dan              Ran              12  ";
char firstName[16];
char lastName2[16];
char score2[16];
       
void formatLine(char s[]){
        size_t i;

        for(i = 0; s[i]!= ' '; i++)
                firstName[i] = s[i];
        for (i = 17; s[i]!= ' '; i++)
                lastName2[i] = s[i];
        for(i = 34; s[i]!= ' '; i++)
                score2[i] = s[i];
        printf("%s, %s:%4s\n", firstName, lastName2, &score2);
        }

        formatLine(dan);
       
        return 0;
}


[edit by md] Fixed the code highlighting

Author:  md [ Fri Oct 03, 2008 3:10 pm ]
Post subject:  RE:Strings

Using your code... are you sure that Ran starts at 17? and that 21 starts at 34?

Also, you need to terminate your string with null characters, as otherwise you get garbage at the end of them.

Author:  dchini [ Fri Oct 03, 2008 4:06 pm ]
Post subject:  Re: Strings

I took your advice and i now have this..... i still get garbage characters though


code:

#include <stdio.h>

int main(void)
{
char dan[]= "Dan              Dan              123 ";


       
void formatLine(char s[]){
        size_t i;
        char firstName[16];
        char lastName2[16];
        char score2[3];

        for(i = 0; s[i]!= ' '; i++)
        {
                firstName[i] = s[i];
        }
        firstName[i] = '\0';




        for (i = 17; s[i]!= ' '; i++)
        {
                lastName2[i-17] = s[i];
        }
        lastName2[i] = '\0';





        for(i = 34; s[i]!= ' '; i++)
        {
                score2[i-34] = s[i];
        }
        score2[i] = '\0';





        printf("%s, %s:%4s", firstName, lastName2, score2);
        }

        formatLine(dan);
       
        return 0;
}

Author:  OneOffDriveByPoster [ Fri Oct 03, 2008 6:59 pm ]
Post subject:  Re: Strings

dchini @ Fri Oct 03, 2008 4:06 pm wrote:
c:
                lastName2[i-17] = s[i];
        lastName2[i] = '\0';
                score2[i-34] = s[i];
        score2[i] = '\0';

Something looks off in the lines I left in, no?


: