【发布时间】:2018-10-03 14:08:54
【问题描述】:
我目前正在为游戏设置高分部分,但由于 std::sort 函数的奇怪行为,我遇到了一个非常奇怪的问题。
我在 C++ 中的 RAD Studio 10.2 (Embarcadero IDE) 中完成所有工作。
所以他是我的代码:
std::string Line;
int count = 0;
int i = 0;
ifstream File("Highscore.txt");
if(File.is_open())
{
while(getline(File, Line))
{
count += 1;
}
File.close();
}
ifstream ReadFile("Highscore.txt");
if(ReadFile.is_open())
{
string *scores = NULL;
scores = new string[count];
while(getline(ReadFile, Line))
{
scores[i] = Line;
i += 1;
}
ReadFile.close();
std::sort(scores, (scores+count));
UnicodeString Uscores1 = scores[0].c_str();
UnicodeString Uscores2 = scores[1].c_str();
UnicodeString Uscores3 = scores[2].c_str();
UnicodeString Uscores4 = scores[3].c_str();
UnicodeString Uscores5 = scores[4].c_str();
LScore1->Caption = Uscores1;
LScore2->Caption = Uscores2;
LScore3->Caption = Uscores3;
LScore4->Caption = Uscores4;
LScore5->Caption = Uscores5;
}
编译器/链接器没有错误,一切正常。 字符串数组被正确填充等等。
但它没有排序。
为了给你看问题,我做了一个截图——在左边你可以看到带有分数的txt文件;右边可以看到排序算法后的输出:
我现在的问题是为什么会这样?
感谢您的帮助
【问题讨论】:
-
它确实排序。如果你想按数字排序,你应该使用数字类型。
-
如果以前没有人告诉过您,请查看我们的页面minimal complete examples。不要发布数据的屏幕截图,将其硬编码到您的示例中。
-
我错了,在发帖几秒后删除了我的评论。
-
当我在示例中的 txtfile 中有 5 个分数并输出分数 [4] 时,输出为 5 = 我的 txtfile 中的第五项。
-
@SamyDressel 您有 5 个分数和 2 个“空”行,它们都是
std::string的有效值。检查count的值