0

我们目前正在学习 C++,我认为这段代码还不需要我们使用指针。

因此,对于答案的建议,请让我知道是否可以在没有指针的情况下完成。

问题:如何比较一个 char 数组,以便您可以按升序对它们进行排序?

细节:

目标:在插入名称时按升序对名称进行排序

我们在这里有什么:

char name[1024]; // which is a part of a Struct 

插入有效。一旦插入。我正在尝试重新排列顺序,以便名称在

升序。

我有:

if (RecordCollection[i].name > RecordCollection[i+1].name) // for comparing 

我想这可能是问题所在?C++可以这样比较吗?比如,比较约翰和艾米

那一行?

After that if statement, I am using swapping the elements so they are in correct order. For example: 
If John[0] the current name is > than Amy[1], then copy John to a temporary. 
Then copy Amy to index[0]. 
Then copy John in temporary to index[1].

在输入这个问题时,我想我需要一个一个地比较字符...... J和A,如果不一样那么

种类。如果相同,则移动到下一个字符,直到找到不同的排序。但后来我不知道如何

得到 char 1 by 1。

4

1 回答 1

0

如果您使用字符串,请参阅strcmp.

男人strcmp

大于零的值表示第一个不匹配的字符 in 的值str1大于 in str2;小于零的值表示相反。

要对数组进行排序,您还可以使用qsort标准 C 库。

#include <string.h>

int
cmp (const void *p, const void *q)
{
  return strcmp (p, q);
}

qsort (RecordName, nelems, 1024, cmp);
于 2013-02-09T16:48:46.980 回答