/* * STRCPY -- show 4 different ways of copying a string * * Usage: strcpy * * Inputs:tring to be copied * Output: 4 copies, each done differently * Exit Code: EXIT_SUCCESS * * Matt Bishop, ECS 36A * April 12, 2024 original version */ #include #include #include /* * macros */ #define MAXLINE 1000 /* maximum allowed line length */ /* * prototypes -- all are different functions that do the same * thing: copy a string from old to new */ void str1copy(char new[], char old[]); void str2copy(char new[], char old[]); void str3copy(char new[], char old[]); void str4copy(char *new, char *old); /* * echo a line from the input to the output */ int main(void) { char buf[MAXLINE]; /* input buffer */ char new[MAXLINE]; /* output buffer */ /* * read a line, then write it out */ while(printf("type away!> "), fgets(buf, MAXLINE, stdin) != NULL){ /* #1 to: copy it to the new buffer and print it */ str1copy(new, buf); printf("1> "); fputs(new, stdout); /* #2: copy it to the new buffer and print it */ str2copy(new, buf); printf("2> "); fputs(new, stdout); /* #3: copy it to the new buffer and print it */ str3copy(new, buf); printf("3> "); fputs(new, stdout); /* #4: copy it to the new buffer and print it */ str4copy(new, buf); printf("4> "); fputs(new, stdout); } /* * say goodbye! */ return(0); } /* * make a copy of a string * * arguments: char old[] original string * char new[] buffer for copy * * returns: nothing, but on return new contains a copy of old * * exceptions: none, but length of old and new are not checked */ void str1copy(char new[], char old[]) { int i; /* counter in a for loop */ /* * do it char by char */ for(i = 0; old[i] != '\0'; i++) new[i] = old[i]; /* tack on the terminator */ new[i] = '\0'; } /* * make a copy of a string * * arguments: char old[] original string * char new[] buffer for copy * * returns: nothing, but on return new contains a copy of old * * exceptions: none, but length of old and new are not checked */ void str2copy(char new[], char old[]) { int i; /* counter in a for loop */ /* * do it char by char */ for(i = 0; old[i]; i++) new[i] = old[i]; /* tack on the terminator */ new[i] = '\0'; } /* * make a copy of a string * * arguments: char old[] original string * char new[] buffer for copy * * returns: nothing, but on return new contains a copy of old * * exceptions: none, but length of old and new are not checked */ void str3copy(char new[], char old[]) { int i; /* counter in a for loop */ /* * do it char by char */ for(i = 0; new[i] = old[i]; i++) ; } /* * make a copy of a string * * arguments: char old[] original string * char new[] buffer for copy * * returns: nothing, but on return new contains a copy of old * * exceptions: none, but length of old and new are not checked */ void str4copy(char *new, char *old) { /* * do it char by char */ while(*new++ = *old++) ; }