alphasil Posted May 21, 2012 at 08:45 PM Report #457254 Posted May 21, 2012 at 08:45 PM Oi ppl; Ainda ando de volta disso e não há meio de pôr isso a dar int gp1_Ques(int id) { FILE *fp; char * lista[1000]; int random, n; fp = fopen("Atividades/gp1.dat","r"); while(1) { rewind(fp); while(random == 0 ) random = rand()%n; while (fgets(lista[n], 256, fp) == lista[n]) n++; // fechar ficheiro fclose(fp); //escolher pergunta srand(time(NULL)); random = rand()%n; } return random; } Este código não dá erro, mas como ponho a fazer print do random escolhido?? Ao correr o programa pára... Já não estou a ver nada.... gmc11
pikax Posted May 21, 2012 at 09:01 PM Report #457258 Posted May 21, 2012 at 09:01 PM o programa nao para porque o tens um while(1) isto significa que e' infinito, para mostrar o random basta fazer um printf 'a variavel do random Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
alphasil Posted May 21, 2012 at 09:23 PM Author Report #457261 Posted May 21, 2012 at 09:23 PM Já estive a ver e rever, alterei para: void gp1_Ques(struct perg *p) { char * lista[1000]; // mil perguntas com tamanho máximo de 255 caracteres int count, random; FILE *f; if ((f = fopen("Atividades/gp1.dat", "rb")) == NULL) { printf("Erro ao abrir ficheiro\n"); } else { count = 0; while (fgets(lista[count], 1000, f) == lista[count]) { count++; } // fechar ficheiro fclose(f); //escolher pergunta random=rand() % count; } printf(random); } variable ‘random’ set but not used line 650 C/C++ Problem passing argument 1 of ‘printf’ makes pointer from integer without a cast line 668 C/C++ Problem Pelos vistos a variavel randomnão está fazer nada e quando a mando imprimir....dá outro warning gmc11
pikax Posted May 21, 2012 at 09:26 PM Report #457262 Posted May 21, 2012 at 09:26 PM o teu printf esta mal devia de estar assim: printf("%d",random); Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
pmg Posted May 21, 2012 at 09:29 PM Report #457263 Posted May 21, 2012 at 09:29 PM Pelos vistos a variavel randomnão está fazer nada e quando a mando imprimir....dá outro warning Para imprimires um valor de tipo int, faz assim: printf("%d", random); Da maneira que estavas a fazer, o compilar tentou interpretar o random (de tipo int) como a string de formatacao (de tipo char *) e queixou-se, avisando-te que essa conversao e ilegal. What have you tried? Não respondo a dúvidas por PM A minha bola de cristal está para compor; deve ficar pronta para a semana. Torna os teus tópicos mais atractivos e legíveis usando a tag CODE para colorir o código!
alphasil Posted May 21, 2012 at 09:56 PM Author Report #457271 Posted May 21, 2012 at 09:56 PM Muito estranho Deu erro Process returned 255 (0xff) e deu janela de erro... gmc11
pikax Posted May 21, 2012 at 10:00 PM Report #457274 Posted May 21, 2012 at 10:00 PM mete aqui o codigo, ja' agora nao queres imprimir a pregunta? Se sim terias que fazer assim: printf("%s\n",lista[random]); Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
alphasil Posted May 21, 2012 at 11:14 PM Author Report #457288 Posted May 21, 2012 at 11:14 PM O código é muito extenso, mas tem a ver com isto struct perg /* Estrutura Questoes Grupo 1 */ { int id; char ques[200]; char op1[15]; char op2[15]; char op3[15]; char op4[15]; int res; }; Para adcionar perguntas void ad_perguntas(struct perg *p) { char buf[30]; FILE *f; if ((f = fopen("gp1.dat", "a+b")) == NULL) { printf("Erro ao abrir ficheiro\n"); } else { //Lê do teclado e grava no ficheiro printf("Introduza o ID da pergunta \n"); fgets(buf, 30, stdin); sscanf(buf,"%d", &p->id); printf("Introduza a pergunta: \n"); fgets(p->ques,200, stdin); printf("Opcao 1: \n"); fgets(p->op1, 15, stdin); printf("Opcao 2: \n"); fgets(p->op2, 15, stdin); printf("Opcao 3: \n"); fgets(p->op3, 15, stdin); printf("Opcao 4: \n"); fgets(p->op4, 15, stdin); printf("Introduza numero da resposta certa \n"); fgets(buf, 30, stdin); sscanf(buf,"%d", &p->res); fwrite(p, sizeof(struct perg), 1 , f); fclose(f); } } void ver_perguntas(struct perg *p) { int retorno, cont = 0; FILE *f; if ((f= fopen("gp1.dat", "rb")) == NULL) { printf("Erro ao abrir ficheiro\n"); } retorno = fread(p, sizeof *p, 1, f); while ( retorno == 1) { cont++; printf("\nId : %d \n", p->id); printf("\nPergunta : %s", p->ques); printf("\nOpcao 1 : %s",p->op1); printf("\nOpcao 2 : %s",p->op2); printf("\nOpcao 3 : %s",p->op3); printf("\nOpcao 4 : %s",p->op4); printf("\nResposta Correta : %d",p->res); printf("\n"); retorno= fread(p, sizeof *p, 1, f); } printf(" \n\n %d perguntas registadas \n", cont); fclose(f); } void edit_perguntas(struct perg *p) { int recno, nofrec=0; char ch; char buf[100]; FILE *fp; fp=fopen("gp1.dat", "rb+"); printf("Introduza o Id a modificar : "); fgets(buf, sizeof buf, stdin); sscanf(buf, "%d", &recno); while(fread(p, sizeof *p, 1, fp)) { nofrec++; printf("sizeof(p) = %d; sizeof *p = %d\n", (int)sizeof(p), (int)sizeof *p); if(p->id==recno) { printf("\nId : %d \n", p->id); printf("\nPergunta : %s", p->ques); printf("\nOpcao 1 : %s",p->op1); printf("\nOpcao 2 : %s",p->op2); printf("\nOpcao 3 : %s",p->op3); printf("\nOpcao 4 : %s",p->op4); printf("\nResposta Correta : %d",p->res); printf("\n"); printf("Quer modificar este registo: ? (S/N)"); fgets(buf, sizeof buf, stdin); sscanf(buf, "%c", &ch); fseek(fp, (nofrec - 1) * sizeof *p, SEEK_SET); if(ch=='S'|| ch=='s') { printf("Introduza a pergunta: \n"); fgets(p->ques,200, stdin); printf("Opcao 1: \n"); fgets(p->op1, 15, stdin); printf("Opcao 2: \n"); fgets(p->op2, 15, stdin); printf("Opcao 3: \n"); fgets(p->op3, 15, stdin); printf("Opcao 4: \n"); fgets(p->op4, 15, stdin); printf("Introduza numero da resposta certa \n"); fgets(buf, sizeof buf, stdin); sscanf(buf, "%d", &p->res); fwrite(p, sizeof *p, 1, fp); printf("Registo modificado \n"); } else { printf("Sem modificacoes efetuadas \n"); } fclose(fp); } } } E por fim o random void gp1_Ques(struct perg *p) { char * lista[200]; // mil perguntas com tamanho máximo de 255 caracteres int count, random; FILE *f; if ((f = fopen("gp1.dat", "rb")) == NULL) { printf("Erro ao abrir ficheiro\n"); } else { count = 0; while (fgets(lista[count], 200, f) == lista[count]) { count++; } // fechar ficheiro fclose(f); //escolher pergunta random=rand() % count; } printf("%s\n",lista[random]); } Eu quero é que ao ler o ficheiro me faça random das perguntas que lá estão, menos a resposta claro. Cumps *Dá erro na mesma com a linha que pôs Obriagdo gmc11
pikax Posted May 21, 2012 at 11:25 PM Report #457291 Posted May 21, 2012 at 11:25 PM tenta saber onde e' que esta' mesmo a dar erros, mete printfs, para saberes em que funcao esta a dar o erro Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
alphasil Posted May 21, 2012 at 11:46 PM Author Report #457294 Posted May 21, 2012 at 11:46 PM o erro ta nesta uitima porque o resto funciona tudo gmc11
pikax Posted May 22, 2012 at 12:06 AM Report #457297 Posted May 22, 2012 at 12:06 AM este while esta' errado while (fgets(lista[count], 200, f) == lista[count]) C nao tem suporte de comparacao de strings Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
bsccara Posted May 22, 2012 at 12:09 AM Report #457298 Posted May 22, 2012 at 12:09 AM Na tua função 'gp1_Ques' a linha 'char * lista[200];' declara um array de 200 ponteiros para caracteres (presumivelmente strings ASCIIZ). Depois a linha 'while (fgets(lista[count], 200, f) == lista[count])' lê um máximo de 199 caracteres da stream 'f' e grava-os no endereço indicado pelo ponteiro gravado na posição 'count' do array 'lista'. O problema é que esse ponteiro (aliás todos os ponteiros do array 'lista') não é inicializado, pelo que aponta para um lado qualquer e obviamente o programa estoura. Tens de usar o malloc para alocar memória para as strings que queres receber, uma vez para cada elemento do array 'lista'. Como as strings carregadas só vão ser usadas nessa função deves libertar o espaço alocado com 'free's no fim da função. este while esta' errado while (fgets(lista[count], 200, f) == lista[count]) C nao tem suporte de comparacao de strings Esse código não compara strings; compara ponteiros, o que é suportado. Se a função fgets fôr bem sucedida retorna o primeiro parâmetro (ponteiro para o buffer) ou um ponteiro nulo se houver uma falha (fim da stream).
pikax Posted May 22, 2012 at 12:23 AM Report #457299 Posted May 22, 2012 at 12:23 AM pois e', acho que o sono, esta.me a afectar... Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender. A beleza de um código está em decompor problemas complexos em pequenos blocos simples. "learn how to do it manually first, then use the wizzy tool to save time." "Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."
alphasil Posted May 22, 2012 at 12:33 AM Author Report #457300 Posted May 22, 2012 at 12:33 AM ok, Vou tentar isso amanhã que agora tou estoirado. Obrigado pessoal. gmc11
HappyHippyHippo Posted May 22, 2012 at 08:28 AM Report #457315 Posted May 22, 2012 at 08:28 AM epa .. esse código é tirado do meu que te apresentei noutro post ... se bem me lembro eu tinha posto: char lista[1000][256]; // mil perguntas com tamanho máximo de 255 caracteres isto porque acho que tinhas problemas com alocação dinâmica de memória IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted May 22, 2012 at 10:19 AM Author Report #457350 Posted May 22, 2012 at 10:19 AM Oi Este aquele exemplo que me deste, juntei as minhas partes mas não tinha alocação dinâmica de memória, pelos vistos é preciso meter isso, vou tentar a ver se funciona, tenho aqui um exemplo e vou tentar adaptá-lo. gmc11
alphasil Posted May 22, 2012 at 11:01 AM Author Report #457359 Posted May 22, 2012 at 11:01 AM Oi ppl; Nem com malloc lá vai, dá crash na mesma. void gp1_Ques(struct perg *p) { char * lista[200]; // mil perguntas com tamanho máximo de 255 caracteres char *copia; int count, random; FILE *f; if ((f = fopen("gp1.dat", "rb")) == NULL) { printf("Erro ao abrir ficheiro\n"); } else { copia=malloc(sizeof *lista); count = 0; while (fgets(lista[count], 200, f) == lista[count]) { count++; } // fechar ficheiro fclose(f); free(copia); //escolher pergunta random=rand() % count; } printf("%s\n",lista[random]); } Está mal inserido o malloc?? gmc11
HappyHippyHippo Posted May 22, 2012 at 11:49 AM Report #457361 Posted May 22, 2012 at 11:49 AM (edited) dividir para conquistar !!! (não testado) #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Pergunta { int id; char ques[200]; char op1[15]; char op2[15]; char op3[15]; char op4[15]; int res; } Pergunta; typedef struct Perguntas { Pergunta * lista; size_t numero; } Perguntas; int allocPerguntas(Perguntas * perguntas) { if ((perguntas->lista = malloc(sizeof(Pergunta) * perguntas->numero)) == NULL) return -1; return 0; } void freePerguntas(Perguntas * perguntas) { free(perguntas->lista); perguntas->lista = NULL; } int readPerguntas(Perguntas * perguntas, char * file) { int count; FILE *f; if ((f = fopen(file, "r+b")) == NULL) return -1; if ((count = fread(perguntas->lista, sizeof(Pergunta), perguntas->numero, f)) != perguntas->numero) { perguntas->numero = count; fclose(f); return -2; } fclose(f); return 0; } int main(void) { Perguntas perguntas; perguntas.numero = 1000; if (allocPerguntas(&perguntas) != perguntas.lista) { printf("Erro a alocar memoria para as perguntas\n"); return -1; } if (readPerguntas(&perguntas, "gp1.dat") == -1) { printf("Erro a abrir o ficheiro de perguntas\n"); return -1; } freePerguntas(&perguntas); return 0; } Edited May 22, 2012 at 11:49 AM by HappyHippyHippo IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
alphasil Posted May 22, 2012 at 01:45 PM Author Report #457378 Posted May 22, 2012 at 01:45 PM (edited) Oi Minha nossa, isto está meio chinês para mim 😄 Já pus o código todo mas dá-me aquele erro de alocação de memória if (allocPerguntas(&perguntas) != perguntas.lista) { printf("Erro a alocar memoria para as perguntas\n"); return -1; Warning: comparison between pointer and integer [enabled by default] Buzz_final.c /Buzz_final/src line 680 C/C++ Problem Naquele if Puseste as estruturas como typedef, tenho de alterar tudo nas minhas funções?? eu tinha assim void ver_perguntas(struct perg *p) { int retorno, cont = 0; FILE *f; if ((f= fopen("gp1.dat", "rb")) == NULL) { printf("Erro ao abrir ficheiro\n"); } retorno = fread(p, sizeof *p, 1, f); while ( retorno == 1) { cont++; printf("\nId : %d \n", p->id); printf("\nPergunta : %s", p->ques); printf("\nOpcao 1 : %s",p->op1); printf("\nOpcao 2 : %s",p->op2); printf("\nOpcao 3 : %s",p->op3); printf("\nOpcao 4 : %s",p->op4); printf("\nResposta Correta : %d",p->res); printf("\n"); retorno= fread(p, sizeof *p, 1, f); } printf(" \n\n %d perguntas registadas \n", cont); fclose(f); } Edited May 22, 2012 at 01:54 PM by alphasil gmc11
HappyHippyHippo Posted May 22, 2012 at 02:30 PM Report #457394 Posted May 22, 2012 at 02:30 PM Warning: comparison between pointer and integer [enabled by default] Buzz_final.c /Buzz_final/src line 680 C/C++ Problem a culpa é minha ... fiz o código sem compilar e testar ... deveria ser assim: if (allocPerguntas(&perguntas) != 0) { IRC : sim, é algo que ainda existe >> #p@p Portugol Plus
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now