问题
I have to write a program that sorts 10 people by height, then by last name. I've got the height down, but i can't get the last name sort to work. I'm trying to use strcmp for it. Any time I try to run it though, it flags an error at the strcmp saying, "[Error] cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int strcmp(const char*, const char*)'" I'm using strcmp because this is for a school assignment and I am limited by my knowledge of c++ and what my professor allows us to use
int main()
{
const int SIZE = 10;
int count = 0;
bool flag = true;
string fileName;
ifstream inputFile;
string firstName[SIZE];
string lastName[SIZE];
int height[SIZE];
cin >> fileName;
inputFile.open(fileName.c_str());
while(count < 10)
{
inputFile >> firstName[count];
inputFile >> lastName[count];
inputFile >> height[count];
count++;
}
//Sort based on height
for(int max = SIZE - 1; max > 0 && flag; max--)
{
flag = false;
for(int line = 0; line < max; line++)
{
if(height[line] > height[line + 1])
{
swap(height[line], height[line + 1]);
swap(firstName[line], firstName[line + 1]);
swap(lastName[line], lastName[line + 1]);
flag = true;
}
}
}
//Sort based on last name if heights are equal
for(int max = SIZE - 1; max > 0 && flag; max--)
{
flag = false;
for(int line = 0; line < max; line++)
{
if(height[line] == height[line + 1])
{
if(strcmp(lastName[line], lastName[line + 1]) > 0)
{
swap(height[line], height[line + 1]);
swap(firstName[line], firstName[line + 1]);
swap(lastName[line], lastName[line + 1]);
flag = true;
}
}
}
}
回答1:
If you insist on using the old strcmp
function, then you should pass lastName[line].c_str()
and lastName[line+1].c_str()
as its argument(s). However, you'd be better off using the std::string::compare()
function provided by the STL:
if (lastName[line].compare(lastName[line + 1]) > 0)
This does much the same thing.
Or even simpler (as Fred Larson has suggested):
if (lastName[line] > lastName[line+1])
来源:https://stackoverflow.com/questions/59036335/how-can-i-alphabetize-strings-from-an-array-in-c