Thread: Problem with reading from file... problem with strings

  1. #1
    Registered User
    Join Date
    Jun 2014
    Posts
    41

    Problem with reading from file... problem with strings

    hi guys.
    so my program saves the info in a file "something.txt"

    i put name, adress(problem here) postal(problem as well)...etc


    but when i try to read it the program treats every single word as a string but in the adress i have 3 words

    how can i solve it?... i will put the code but some words are in portuguese(i'm from portugal)

    the ones that give problem are "morada" and "postal" (because i have to put 0000-000 and when i try to open appears in one line 0000 and on another line -000)


    Code:
    void mostrarcont(dados* contacto)
    {
    	int j = 0;
    
    
    	
    	for (j = 0; j<i; j++)
    	{
    		printf("\t%d->   \n\tNome:  %s |", j + 1, contacto[j].nome);
    		fflush(stdin);
    		printf(" \n\tNumero de Aluno ISEL: %s |", contacto[j].numero);
    		fflush(stdin);
    		printf(" \n\tMorada: %s |", contacto[j].morada);
    		fflush(stdin);
    		printf(" \n\tCodigo Postal: %s |", contacto[j].postal);
    		fflush(stdin);
    		printf(" \n\tE-Mail: %s |", contacto[j].email);
    		fflush(stdin);
    		printf(" \n\tNumero de telefone: %d |", contacto[j].telefone);
    		fflush(stdin);
    		printf(" \n\tNota final de FP: %d |", contacto[j].FP);
    		fflush(stdin);
    		printf(" \n\tNota final de AM1: %d |", contacto[j].AM1);
    		fflush(stdin);
    		printf(" \n\tNota final de SD: %d |", contacto[j].SD);
    		fflush(stdin);
    		printf(" \n\tNota final de ALGA: %d |", contacto[j].ALGA);
    		fflush(stdin);
    		printf(" \n\tNota final de CM: %d\t\n\n\n |", contacto[j].CM);
    		fflush(stdin);
    	}
    }

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    1. do not use fflush(stdin) - it is undefined
    2. Show us the code that reads file - not the code that prints incorrectly read data
    3. It would be good idea to show us the definition of your struct if the code reads data into it as well as sample file you create fro reading.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    Code:
    typedef struct {
    	char nome[100], email[50], morada[100], postal[20], numero[20];
    	int telefone, FP, SD, AM1, ALGA, CM;
    }dados;


    Code:
    void abrir(dados *contacto)
    {
        FILE *f;
        char nome[100], email[50], morada[100], postal[20], numero[20];
        int telefone, FP, SD, AM1, ALGA, CM;
    
    
        //printf("insira o caminho do ficheiro\n");
        //scanf("%s", &nfich);
    
    
        f = fopen("teste.txt", "r");
        if (f == NULL)
        {
            printf("erro ao abrir ficheiros");
        }
        else
        {
            while (!feof(f))
            {
                fscanf(f, " %s %s %s %s %s %d %d %d %d %d %d", nome,numero, morada, postal, email, &telefone, &FP, &AM1, &SD, &ALGA, &CM);
                strcpy(contacto[i].nome, nome);
                strcpy(contacto[i].numero, numero);
                strcpy(contacto[i].morada, morada);
                strcpy(contacto[i].postal, postal);
                strcpy(contacto[i].email, email);
                contacto[i].telefone = telefone;
                contacto[i].FP = FP;
                contacto[i].AM1 = AM1;
                contacto[i].SD = SD;
                contacto[i].ALGA = ALGA;
                contacto[i].CM = CM;
                i++;
            }
            fclose(f);
        }
    }
    should i put gets() instead?

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    but when i try to read it the program treats every single word as a string but in the adress i have 3 words
    By default the scanf() series of functions stop processing strings when a whitespace character is encountered. You my want to consider using fgets() instead of fscanf(). And if you do stick with fscanf() you should specify the proper width specifier to limit the number of characters this function will retrieve to avoid possible array overruns.

    Jim

  5. #5
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    so i need to put?
    fgets(f," %s", something);
    fgets();
    fgets();

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Did you read any documentation for that function? It sure doesn't look like it.

    Jim

  7. #7
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    sorry

    with this? fgets(buffer, buffer_size, fd)

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I don't know, what are buffer, buffer_size, and fd?

    Have you tried to use this function in your code?

    Also please show a sample of both the input and show how your structure was defined.

    Jim

  9. #9
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    my input function
    Code:
    void f_adicionar(dados* contacto)
    {
    
    
    	if (i<total)
    	{
    		printf("\nIntroduza o Nome:  ", i + 1);
    		fflush(stdin);
    		gets(contacto[i].nome);
    		printf("Introduza o Numero de Aluno ISEL:  ", i + 1);
    		fflush(stdin);
    		gets(contacto[i].numero);
    		printf("Introduza a Morada:  ", i + 1);
    		fflush(stdin);
    		gets( contacto[i].morada);
    		printf("Introduza o Codigo Postal:  ", i + 1);
    		fflush(stdin);
    		gets(contacto[i].postal);
    		printf("Introduza o email:  ", i + 1);
    		fflush(stdin);
    		scanf(" %[^\n]s", contacto[i].email);
    		printf("Introduza o telefone:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d", &contacto[i].telefone);
    		printf("Nota Final de FP:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d", &contacto[i].FP);
    		printf("Nota Final de AM1:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d", &contacto[i].AM1);
    		printf("Nota Final de SD:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d", &contacto[i].SD);
    		printf("Nota Final de ALGA:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d", &contacto[i].ALGA);
    		printf("Nota Final de CM:  ", i + 1);
    		fflush(stdin);
    		scanf(" %d\n\n\n", &contacto[i].CM);
    		i++;
    	}
    	else
    	{
    		printf("a lista esta cheia");
    	}
    	guardar(contacto);
    }

    then the save function

    Code:
    void guardar(dados *contacto)
    {
    	FILE *f;
    	//char nfich[20];
    	int j = 0;
    
    
    	//printf("insira o caminho do ficheiro\n");
    	//scanf("%s", &nfich);
    
    
    	f = fopen("teste.txt", "a");
    
    
    
    
    	for (j = 0; j<i; j++)
    	{
    		fprintf(f, "\n%s ", contacto[j].nome);
    		fflush(stdin);
    		fprintf(f, " %s ", contacto[j].numero);
    		fflush(stdin);
    		fprintf(f, " %s ", contacto[j].morada);
    		fflush(stdin);
    		fprintf(f, " %s ", contacto[j].postal);
    		fflush(stdin);
    		fprintf(f, " %s ", contacto[j].email);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].telefone);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].FP);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].AM1);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].SD);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].ALGA);
    		fflush(stdin);
    		fprintf(f, " %d ", contacto[j].CM);
    		fflush(stdin);
    	}
    
    
    
    
    	printf("Dados guardados com suscesso!!! \n");
    	fclose(f);
    }

    the open file code... fgets is the way i put it??
    Code:
    void abrir(dados *contacto)
    {
    	FILE *f;
    	char nome[100], email[50], morada[100], postal[20], numero[20];
    	int telefone, FP, SD, AM1, ALGA, CM;
    
    
    	//printf("insira o caminho do ficheiro\n");
    	//scanf("%s", &nfich);
    
    
    	f = fopen("teste.txt", "r");
    	if (f == NULL)
    	{
    		printf("erro ao abrir ficheiros");
    	}
    	else
    	{
    		while (!feof(f))
    		{
    			fgets(nome,100,f);
    			strcpy(contacto[i].nome, nome);
    			strcpy(contacto[i].numero, numero);
    			strcpy(contacto[i].morada, morada);
    			strcpy(contacto[i].postal, postal);
    			strcpy(contacto[i].email, email);
    			contacto[i].telefone = telefone;
    			contacto[i].FP = FP;
    			contacto[i].AM1 = AM1;
    			contacto[i].SD = SD;
    			contacto[i].ALGA = ALGA;
    			contacto[i].CM = CM;
    			i++;
    		}
    		fclose(f);
    	}
    }

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I really don't know what those first two horrible sinppets are all about but you have the fgets() call correct in the final snippet, provided that "nome" is the only value on the line.

    However I really don't understand the purpose of the temporary variable nome. Why not just use the structure variable instead?

    I also don't see where you're actually retrieving the rest of the variables.

    Jim

  11. #11
    Registered User
    Join Date
    Jun 2014
    Posts
    9
    Would it help to "borrow" from excell and use comma or tap seperations instead of spaces, as adresses could contain spaces. Further why not read the entire line and process after ?

  12. #12
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Fact - Beethoven wrote his first symphony in C

  13. #13
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    i'm not a native english speaker so i have to make a effort to understand


    main menu:
    1-input(to put on file)
    2-open(to show on screen)
    if i just wanted to receive the data from the keyboard(one menu) and some parts as strings, then save(save function) it and close the program, then open the program and acess the file and put it on the screen.

    how do i do that?

    1st
    gets(nome)
    fputs()????

    2nd
    then save

    3rd
    the open part, how do i show it on screen??
    fgets()
    ????

  14. #14
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    gets(nome)
    No, never, Never, NEVER use gets()! This function can never be used safely and is no longer available in the current C standard. Use fgets() instead.

    Never use fflush() on an imput stream, like stdin, since that invokes undefined behavior.

    Try to stick to fgets() where ever possible, switching between numeric input and character input can be problematic because the numeric input leaves the end of line character behind in the input buffer.

    Also note that when using fgets() you will need to remove the end of string character, if present.


    Also please show your structure definition.

    Jim

  15. #15
    Registered User
    Join Date
    Jun 2014
    Posts
    41
    is this the struct definition???

    Code:
    typedef struct {
        char nome[100], email[50], morada[100], postal[20], numero[20];
        int telefone, FP, SD, AM1, ALGA, CM;
    }dados;

    so if i input information with the keyboard i should use fgets()? shouldn't be gets() because the input is the keyboard? i though that fgets() was to get the string from the file.


    ok fflush and stdin out got it

    i'm learning more now that in classes

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem reading file
    By coder_009 in forum C Programming
    Replies: 10
    Last Post: 01-15-2008, 01:22 PM
  2. problem with reading from file.
    By esi in forum C Programming
    Replies: 5
    Last Post: 06-23-2007, 02:50 PM
  3. Problem with reading strings
    By goron350 in forum C++ Programming
    Replies: 8
    Last Post: 06-05-2005, 12:05 AM
  4. File Reading Problem
    By Tarkad in forum C++ Programming
    Replies: 3
    Last Post: 03-30-2005, 10:49 AM
  5. Problem reading file into array of strings
    By myrddinb in forum C Programming
    Replies: 7
    Last Post: 03-26-2005, 12:12 AM