问题描述
我必须编写一个程序,该程序按身高,然后按姓氏对10个人进行排序.我已经降低了身高,但是我无法使姓氏起作用.我正在尝试使用strcmp.但是,无论何时我尝试运行它,它都会在strcmp处标记一个错误,指出"[错误]无法将参数'1的'std :: string {aka std :: basic_string}'转换为'const char *' 'to'int strcmp(const char *,const char *)'"我之所以使用strcmp,是因为这是用于学校作业,并且由于我对c ++的了解以及我的教授允许我们使用的内容而受到限制
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;
}
}
}
}
推荐答案
如果您继续使用旧的strcmp
函数坚持,则应将lastName[line].c_str()
和lastName[line+1].c_str()
作为其参数传递(s).但是,最好使用STL提供的std::string::compare()
函数:
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)
这做同样的事情.
或更简单(如 Fred Larson 所建议的那样):
Or even simpler (as Fred Larson has suggested):
if (lastName[line] > lastName[line+1])
这篇关于如何在C ++中按字母顺序排列数组中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!