Question:
listing 3 or more names alphabetically on c++ program?
?
2009-07-16 19:20:17 UTC
i am stumped on how to list 3 or more names alphabetically on a c++ program. This is what i have
if (strcmp(name1, name2, name3) <0)
cout<< name1<if(strcmp(name1,name2,name3)>0
cout<
what am i doing wrong?
Three answers:
David
2009-07-16 21:05:46 UTC
you are misusing strcmp. using alot of if statement is a really long and unnessery work you doing. Consider using one of c++’s standard template library (STL) container like a vector or a list as they often have nice functions to help you manipulate tham better than a basic array or a list of variables.



For example, using a list:



#include

#include

#include

#include

using namespace std;



int main() {

     list names;

     names.push_back("bb");

     names.push_back("cc");

     names.push_back("dd");

     names.push_back("aa");



     names.sort();



     for (list::iterator name = names.begin(); name != names.end(); name++ ) {

          cout << *name << endl;

     }

     system("pause");

     return 0;

}



will output:



aa

bb

cc

dd
?
2016-05-26 11:27:44 UTC
Not bad so far, but you don't have any sort of data structure to put all the individual member structs into, in order to be able to sort them. I would probably suggest using a STL container, like a Vector. You could do it yourself with pointers, but it hardly seems worth bothering because a Vector has a built in sort method. The linear file you are reading them in from could also be used, but it would be much slower. You could have to do a bubble sort, where you traverse in 2 nested for loops, swapping 2 member structs at a time, and only those 2 needing to be in memory.
2009-07-16 20:53:03 UTC
You are misusing the function strcmp(). Here's how it works.



http://xoax.net/comp/cpp/reference/cstring/strncmp.php


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...