我必须编写一个程序,将 10 个人按高度排序,然后按姓氏排序。我已经降低了高度,但我无法对姓氏进行排序。我正在尝试为此使用 strcmp。每当我尝试运行它时,它都会在 strcmp 上标记一个错误,说,"[Error] cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1 ' to 'int strcmp(const char*, const char*)'" 我使用 strcmp 是因为这是一项学校作业,我受限于我对 c++ 的了解以及我的教授允许我们使用的内容
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;
}
}
}
}
最佳答案
如果您坚持使用旧的strcmp
函数,那么您应该传递lastName[line].c_str()
和 lastName[line+1].c_str()
作为其参数。但是,您最好使用 STL 提供的 std::string::compare()
函数:
if (lastName[line].compare(lastName[line + 1]) > 0)
这做同样的事情。
或者更简单(如 Fred Larson 所建议的):
if (lastName[line] > lastName[line+1])
关于c++ - 如何在 C++ 中按字母顺序排列数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59036335/