To get the names and punctuation, as the size of the name and punctuation characters are different, we can use fscanf to accomplish this task.
We would have for example:
fscanf(pont_arq, "%s %d\n", nome, &pontuacao);
As for the ordination we would have several ways to accomplish this task.
I think the right way would be for you to create a priority list data structure and a player struct by inserting them in an orderly way in this list. You could also add to the list anyway and use a sorting algorithm (Sort) like bubblesort, heapsort, quicksort, using as a score sort parameter.
Another way maybe simpler but less organized would be you work with a vector of names, another vector with the scores corresponding to the names and so sort the two vectors using punctuation as parameter of ordering.
I will perform an implementation of the last option cited because it is the simplest. I also used bubblesort as the sorting algorithm. I decided to do it in a static way, but if it is not possible to define the line size of the file use malloc to perform the players dynamic instantiation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//algoritmo de sort, perceba que aqui eu ordeno os dois vetores (nome e pontuação)
void bubbleSort(int* pontuacao, char nomes[10][255], int tamanho)
{
int i;
int trocou;
do
{
trocou = 0;
for (i=tamanho; i > 0; i--)
{
if (pontuacao[i] > pontuacao[i-1])
{
int pAux;
char nAux[255];
pAux = pontuacao[i];
strcpy(nAux, nomes[i]);
pontuacao[i] = pontuacao[i-1];
strcpy(nomes[i], nomes[i-1]);
pontuacao[i-1] = pAux;
strcpy(nomes[i-1], nAux);
trocou = 1;
}
}
}while (trocou);
}
void ranking(){
//system("clear");
printf("\n ######- Ranking de Jogadores -######\n");
printf(" \n");
printf(" NOME - PONTOS \n");
printf(" \n");
// cria ponteiro de arquivo
FILE * pont_arq;
//abrindo o arquivo_frase em modo "somente leitura"
pont_arq = fopen("data.txt", "r");
// cria matriz para 10 nomes (poderia ser dinamico) e array de pontuações
char nomes[10][255];
int pontuacoes[10];
//variaveis que irá receber o nome ea pontuação do arquivo
char nome[255];
int pontuacao;
//quantidade de jogadores
int tamanho = 0;
//lê do arquivo
while(fscanf(pont_arq, "%s %d\n", nome, &pontuacao) != EOF)
{
strcpy(nomes[tamanho],nome);
pontuacoes[tamanho] = pontuacao;
tamanho++;
}
//Ordena
bubbleSort(pontuacoes, nomes, tamanho);
//Imprime
int i;
for (i=0; i<tamanho; i++)
{
printf("%s %d\n", nomes[i], pontuacoes[i]);
}
fclose(pont_arq);
//getch();
//system("PAUSE");
//carregaMenu();
}
Post your file structure so we can help you
– Roberto de Campos
all on the same line?
– Roberto de Campos
No no . I hit there in the post agr. With spaces and everything.
– Marthaus Lucas