I'm trying to understand strcmp and not having much luck with it. What Im trying to do is input and compare 7 character strings with strcmp, re-order them accordingly and print out the result. I realize that scanf isnt the best thing to use but for the purposes of my program it works. I tried to be as simplistic as possible, and documented everything.
When I remove the compare two strings section, everything works. The input and output print correctly.
The two things my code does is one, a white space character terminates the string and puts whatever follows the white space into the next row of the array. The second is strcmp doesnt seem to work as I have it, and documentation hasnt been very easy to find.Code:#include <stdio.h> #include <string.h> #include <ctype.h> #define N_STRINGS 7 int main(void) { // MAIN VARIABLE INITIALIZATION// int cnt; //Intializes counter for display/accessing the array row int result; // Gives strcmp a place to put its output char w[N_STRINGS][100]; //Initializes the string array to the number of (N_STRINGS) char tmp; // Initializes the temp variable to swap strings // MAIN VARIABLES END //INTRODUCTION// printf("%s %d %s","This program will take", N_STRINGS,"lines of input and re-order them alphabetically\n"); for (cnt = 0; cnt < N_STRINGS; ++cnt) // For statement to fill the array if(w != '\n') //Continues to fill the buffer until newline is entered from the keyboard { printf ("Enter line number %d\n", cnt + 1); scanf("%s", w[cnt]); } printf("%s","The lines you entered were:\n"); //Prints each line of the array using the line variable for (cnt = 0; cnt < N_STRINGS; ++cnt) printf("w[%d] = %s\n", cnt, w[cnt]); //COMPARE THE TWO STRINGS USING STRCMP// for (cnt = 0; cnt < N_STRINGS; ++cnt) { result = strcmp(*w[cnt], *w[cnt + 1]); if (result > 0) { tmp = *w[cnt]; *w[cnt] = *w[cnt + 1]; *w[cnt + 1] = tmp; } } //OUTPUT// printf("%s\n","Here is your sorted output."); printf("%s\n\n","Strings are sorted alphabetically"); for (cnt = 0; cnt < N_STRINGS; ++cnt) printf("w[%d] = %s\n", cnt, w[cnt]); return 0; }



LinkBack URL
About LinkBacks


