Friday, July 31, 2009

C string manipulation?

Hello, I am trying to write c function that will allow me to input 2 arguments in stdin in which the first argument will translate into argument 2.





Example : abc(argument 1) xyz(argument 2)


a -%26gt; x


b -%26gt; y


c -%26gt; z





If you're familiar with unix, you might recognize this as the tr utility.





What I have so far is this:





int translate(char str1[], char str2[]){





while ((str1[] = getchar()) != EOF)


if (str1[] == str2[])


putchar(str2[]);


else


putchar(str1[]);


}





I'm not really sure if that's correct because I just used the standard while loop for copying a single character and replaced it with an array instead.





Any help would be appreciated.

C string manipulation?
First, there is no evidence that the two str?[] arrays are 4 or greater. Let us assume they are and that you have a means for error checking.


2. EOF !=NULL. NULL ('\0') is usually used to terminate arrays of char such as we use as strings. As I read this routine, your routine accepts input into str1 until it receives a Ctl-D (in Unix) or a Ctl-Z (in Windoze). It checks to see if str1 is equal to str2. If it is it writes str2 to the screen, or else it writes str1 to the screen. There is no length checking or anything else.





I would separate each and every action a bit more. These "arrays" function as chars. Without actually checking I see nothing to increment their positions, and the only place that would be affected would be str1[0] which would be written over and written over until EOF was received.





While no expert I just had to use tr for housekeeping the other day because I'm way too fancy with my directories and that's not how it functions. Remember, if you process a string with no NULL termination you risk a segmentation fault.


No comments:

Post a Comment