Thread: Errors with struct and I/O

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    154

    Errors with struct and I/O

    Hi

    Im new in this site and [COLOR=#22229C !important]looking for some[/COLOR][COLOR=#22229C !important]help with[/COLOR] a code i have

    Code:

    Code:
    struct perg           /* Estrutura Questões */
    {  int id;  char ques[200]; 
     char op1[15]; 
     char op2[15]; 
     char op3[15]; 
     char op4[15]; 
     int res;};
    
    void ad_perguntas()
    {    struct perg *per;    
    int quantos;     
    printf("Quantos registos quer criar?: ");     
    scanf("%d", &quantos);     
       per = malloc(sizeof(struct perg) * quantos);     
       int n;     
       for (n = 0; n < quantos; n++)     
       {            
    printf("Introduza ID para a pergunta: \n");            
    fgets(&per[n].id, sizeof(int), stdin);            
    printf("Introduza a pergunta: \n");            
    fgets(per[n].ques, 200, stdin);            
    printf("Opção 1 : \n");            
    fgets(per[n].op1, 200, stdin);            
    printf("Opção 2 :\n");            
    fgets(per[n].op2, 200, stdin);            
    printf("Opção 3 : \n");            
    fgets(per[n].op3, 200, stdin);            
    printf("Opção 4 : \n");            
    fgets(per[n].op4, 200, stdin);            
    printf("Introduza o número da resposta correta: \n");            fgets(&per[n].res, sizeof(int), stdin);     
       }     
       FILE* data;     
          if ( (data = fopen("data.txt", "a")) == NULL )     
          {               printf("Erro \n");           }     
          for (n = 0; n < quantos; n++)     
          {     
          fprintf(data, "%p\n - %s %s|%s|%s|%s|Resposta correta: %d\n \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, &per[n].res);     
          fclose(data);     
          menu_admin();     
          }     
      }


    1º - I have several warnings in fgets

    Description Resource [COLOR=#22229C !important]Path[/COLOR] Location Type
    passing argument 1 of ‘fgets’ from incompatible pointer type [enabled by default] Trabalho Final.c /Trabalho Final/src line 54 C/C++ Problem

    2º After i choose how many questions i'm gonna add he jump until the question, can't choose an id to the question.

    3º the text comes like this

    10 - Clube ganhador
    -benfica
    |porto
    |braga
    |nacional
    |Resposta correta: 2609

    I would like to have all in one line and the last record he gives a memory address and not 1,2,3 or 4..

    Any help would be grateful

    Thanks

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    1º - you cannot use fgets() to read an int.
    2º - this happens when you mix scanf() and fgets().
    search the forum. this problem comes up nearly every day lately.
    3º - fgets() returns a string including the trailing \n.
    you have to remove it.
    Code:
    fgets(per[n].op1, 200, stdin);
    perg.op1 is defined to hold only 15 chars
    use
    Code:
    fgets(per[n].op1, 14, stdin);
    same for op2, op3 and op4
    Kurt

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    use fread for ints rather than fgets which is only for strings

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    Quote Originally Posted by dmh2000 View Post
    use fread for ints rather than fgets which is only for strings
    Nah, fread is for binary data and he's reading from stdin. Good luck trying to get the user to input an int in it's native representation on that machine . He needs to fgets into a temporary buffer and use ​sscanf to turn it into an int.

  5. #5
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Quote Originally Posted by dmh2000 View Post
    use fread for ints rather than fgets which is only for strings
    I have already changed this to:

    Code:
    void ad_perguntas()
    {
    	struct perg per[100];
    	int quantos;
    	char tmp2[200];
    	char tmp[200];
    	char tmp1[200];
    	 printf("Quantos registos quer criar? ");
    	 fgets(tmp2, sizeof tmp2, stdin);
    	 quantos=strtol(tmp2, NULL, 10);
    	    int n;
    	    for (n = 0; n < quantos; n++)
    	    {
    	    	printf("Introduza ID para a pergunta: \n");
    	    	fgets(tmp, sizeof tmp, stdin);
    	    	per[n].id = strtol(tmp, NULL, 10);
    	    	printf("Introduza a pergunta: \n");
    	    	fgets(per[n].ques, 200, stdin);
    	    	printf("Opção 1 : \n");
    	    	fgets(per[n].op1, 14, stdin);
    	    	printf("Opção 2 :\n");
    	    	fgets(per[n].op2, 14, stdin);
    	    	printf("Opção 3 : \n");
    	    	fgets(per[n].op3, 14, stdin);
    	    	printf("Opção 4 : \n");
    	    	fgets(per[n].op4, 14, stdin);
    	    	printf("Introduza o número da resposta correta: \n");
    	    	fgets(tmp1, sizeof tmp1, stdin);
    	    	per[n].res = strtol(tmp1, NULL, 10);
    	    }
    	    FILE* data;
    	       if ( (data = fopen("data.txt", "a")) == NULL )
    	       {
    	           printf("Erro \n");
    	       }
    	       for (n = 0; n < quantos; n++)
    	       {
    	       fprintf(data, "%d - %s %s|%s|%s|%s|Resposta correta: %d \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, &per[n].res);
    	       fclose(data);
    	       menu_admin();
    	       }
    	   }
    
    but right now it stops at the first question and i have an warning in the fprintf(data, "%d - %s %s|%s|%s|%s|Resposta correta: %d \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, &per[n].res);
    
    format ‘%d’ expects argument of type ‘int’, but argument 9 has type ‘int *’ [-Wformat]
    
    any help please?
    
    thanks

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    > format ‘%d’ expects argument of type ‘int’, but argument 9 has type ‘int *’ [-Wformat]
    Remove the & from per[n].res.

  7. #7
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    The warning has disapear

    But the program stucks at the first question

    Code:
    printf("Quantos registos quer criar? ");
    	fgets(tmp2, sizeof tmp2, stdin);
    	quantos=strtol(tmp2, NULL, 10);

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    This may sound silly, but are you typing a number and pressing enter? What exactly is the input you give?

    EDIT: What do you mean by stuck? Does it not let you type any input? Does it let you type input, but it doesn't do anything after that. Where exactly is it stuck?

  9. #9
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    oops, sorry you're right. i just saw this : '1º - you cannot use fgets() to read an int.' and mentally answered that question

  10. #10
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    Thanks for your reply

    I want to give the chance for an user to choose how many questions he wants to add into the database, for that i use a loop statement with this var (quantos), after he's choices the loop must be executed how many times the loop is valid, so i need to put a number and press ENTER.

    anything wrong?

    regards

  11. #11
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    try printing tmp2. like
    Code:
    printf("tmp2='%s'\n", tmp2);
    I could imagine that you get an empty string or a '\n' from a scanf() somewhere else in your program. In that case quantos would be 0.
    Kurt

  12. #12
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    He gives me:

    Quantos registos quer criar? tmp2='
    '

    ?? Don't know where he gets thos ' '

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,907
    It sounds like Kurt is right. I put the code you posted in a program by itself and it works fine. There must be some other code you call before ad_perguntas that leaves a newline in the input buffer somewhere. You would need to post all of your code.

  14. #14
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    ?? Don't know where he gets thos ' '
    They are from the format string. But it still proves that there is some leftover \n from another scanf() call.
    Kurt

  15. #15
    Registered User
    Join Date
    Apr 2012
    Posts
    154
    All my code

    Code:
    /*
     ============================================================================
     Name        : Trabalho.c
     Author      : gmc
     Version     : 1.0
     Copyright   : GMC
     Description : Buzz
     ============================================================================
     */
    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    
    //******************************************************************************************************
    //Estruturas a serem usadas
    
    
    struct perg           /* Estrutura Questões */
    {
      int id;
      char ques[200];
      char op1[15];
      char op2[15];
      char op3[15];
      char op4[15];
      int res;
    };
    
    
    struct jogador 			 /* Estrutura Utilizadores */
    {
      char nome[100];
      char id[100];
      char pass[100];
      int log;
    };
    
    
    //função para adcionar perguntas num ficheiro
    void ad_perguntas()
    {
    	struct perg per[100];
    	int quantos;
    	char tmp2[200];
    	char tmp[200];
    	char tmp1[200];
    	printf("Quantos registos quer criar? ");
    	fgets(tmp2, sizeof tmp2, stdin);
    	quantos=strtol(tmp2, NULL, 10);
    	printf("tmp2='%s'\n", tmp2);
    	int n;
    	    for (n = 0; n < quantos; n++)
    	    {
    	    	printf("Introduza ID para a pergunta: \n");
    	    	fgets(tmp, sizeof tmp, stdin);
    	    	per[n].id = strtol(tmp, NULL, 10);
    	    	printf("Introduza a pergunta: \n");
    	    	fgets(per[n].ques, 200, stdin);
    	    	printf("Opção 1 : \n");
    	    	fgets(per[n].op1, 14, stdin);
    	    	printf("Opção 2 :\n");
    	    	fgets(per[n].op2, 14, stdin);
    	    	printf("Opção 3 : \n");
    	    	fgets(per[n].op3, 14, stdin);
    	    	printf("Opção 4 : \n");
    	    	fgets(per[n].op4, 14, stdin);
    	    	printf("Introduza o número da resposta correta: \n");
    	    	fgets(tmp1, sizeof tmp1, stdin);
    	    	per[n].res = strtol(tmp1, NULL, 10);
    	    }
    	    FILE* data;
    	       if ( (data = fopen("data.txt", "a")) == NULL )
    	       {
    	           printf("Erro \n");
    	       }
    	       for (n = 0; n < quantos; n++)
    	       {
    	       fprintf(data, "%d - %s %s|%s|%s|%s|Resposta correta: %d \n",per[n].id, per[n].ques, per[n].op1, per[n].op2, per[n].op3, per[n].op4, per[n].res);
    	       fclose(data);
    	       //menu_admin();
    	       }
    	   }
    
    
    void ver_perguntas()
    {
    	{
    char c;
    	    FILE* data;
    	    if ((data = fopen("data.txt", "rb")) == NULL)
    	    {
    	        printf("Erro ao abrir ficheiro\n");
    	    }
    	    struct perg* per;
    	    per= malloc(sizeof(*per));
    	    fread(&per[0], sizeof(struct perg), 100, data);
    	    free(per);
    	    fclose(data);
    	    printf("Quer voltar ao menu anterior? \n");
    	    scanf("%c", &c);
    	    if (c=='s'||c=='S')
    	    {
    	    	menu_ad();
    	    }
    	}
    }
    //Funções a serem usadas
    void estrelas()
    {
    	int i;
    	for (i=0; i<=20; i++)
    	{
    		putchar('*');
    	}
    	//Poe caracter vazio
    	putchar('\n');
    }
    
    
    void menu_principal()
    {
    
    
    	int op;
    	//Escreve string
    		puts("------------MENU-------------------\n");
    		printf("1 - Entrar como Administador \n");
    		printf("2 - Entrar como jogador \n");
    		printf("3 - Sair da aplicação \n");
    		printf("Escolha uma das opções:\n");
    		scanf("%d", &op);
    
    
    				switch (op)
    				{
    				case 1:
    					//chama função admin
    					adm();
    					break;
    				case 2:
    					//chama estrutura 2
    					jogo();
    					break;
    				case 3:
    						//chama estrutura 3
    					exit(0);
    					break;
    				default:
    					printf("Opção inválida");
    				}
    }
    void jogo()
    {
    	int op1;
    	    printf("1 - Jogo curto (2 perguntas)\n");
    		printf("2 - Jogo médio (4 perguntas)\n");
    		printf("3 - Jogo longo (8 perguntas)\n");
    		printf("4 - Voltar ao menu inicial \n");
    		printf("Escolha o tipo de jogo desejado:\n");
    		scanf("%d", &op1);
    
    
    		switch (op1)
    		{
    		case 1:
    			//chama estrutura 1
    			printf("escolheu 1");
    			break;
    		case 2:
    			//chama estrutura 2
    			printf("escolheu 2");
    			break;
    		case 3:
    			//chama estrutura 3
    			printf("escolheu 3");
    			break;
    		case 4:
    				//chama estrutura 3
    				menu_principal();
    				break;
    		default:
    			printf("Valor inválido");
    		}
    }
    
    
    void menu_ad()
    {
    	int op;
    	printf("1 - Inserir perguntas na BD \n");
    	printf("2 - Ver perguntas da BD \n");
    	scanf("%d", &op);
    	switch (op)
    	{
    	case 1:
    		ad_perguntas();
    		break;
    	case 2:
    		ver_perguntas();
    	default:
    		printf("Escolha inválida \n");
    	}
    }
    
    
    adm()
    {
    	char login [10], pass [10];
    	int x, a=1 , b=1;
    	for (x=0; x<3; x++)
    	{
    		printf("Utilizador: \n");
            scanf("%s", login);
    		printf("Password: \n");
    		scanf("%s", pass);
    		a= strcmp(login,"gil");
    		b= strcmp(pass, "123");
    		if (a==0 && b==0)
    		{
    			printf("Bem vindo \n");
    			//Chamar um menu de escolha para o Admin
    			menu_ad();
    			x=5;
    			break;
    		}
    		else
    		{
    			printf("Dados Utilizador ou Pass errados....Tente de novo \n");
    		}
    	}
    	if (x==3)
    	{
    	printf("Tentativas exedidas, vai voltar ao menu inicial..\n");
    	menu_principal();
    	}
    }
    
    
    
    
    int main(void)
    {
    	estrelas();
    	printf("BEMVINDOS AO BUZZ \n");
    	estrelas();
    	putchar('\n');
    	menu_principal();
    
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 03-06-2011, 09:12 PM
  2. struct holding data inside a linked list struct
    By icestorm in forum C Programming
    Replies: 2
    Last Post: 10-06-2009, 12:49 PM
  3. Making a (atom) class in a (struct) class makes big errors!
    By Yarin in forum Windows Programming
    Replies: 4
    Last Post: 09-11-2007, 07:18 PM
  4. Script errors - bool unrecognized and struct issues
    By ulillillia in forum Windows Programming
    Replies: 10
    Last Post: 12-18-2006, 04:44 AM
  5. Struct errors...
    By Cale in forum C Programming
    Replies: 2
    Last Post: 12-12-2002, 11:49 PM