在C中读取高分/分析字符串

时间:2016-09-01 01:44:23

标签: c string sorting

我有一个高分数文件,其中存储了名称和分数。每个条目除以;名称和分数之间是 - 这是一个例子:

15-Player One;10-Player Two;20-Player Three;10-Player Four;8-Player Five

我现在正在将文件的内容读入 char * buffer

我的目标是将每个条目与另一个条目分开[有点像 buffer.Split(';') for C#]并按升序打印列表。

有关如何以最简单的方式进行操作的专业提示?我目前正在停电......

1 个答案:

答案 0 :(得分:0)

从string.h中,您可以使用strtok():

#include <string.h>
#include <stdio.h>

int main()
{
    char scores[256] = "15-Player One;10-Player Two;20-Player Three;10-Player Four;8-Player Five";
    const char separator[2] = ";";
    char *entry;

    // Get the first entry
    entry = strtok(scores, separator);

    // Get all the others
    while (NULL != entry)
    {
        printf("%s\n", entry);

        /* You can also use it here to separate the actual score from the player */

        entry = strtok(NULL, separator);
    }

    return 0;
}