Not stopping processing file

2

Why are not you stopping the comparison?

/*7.    Faça um programa que leia uma sequência de nomes no formato “nome sobrenome” e armazene-os em um arquivo texto.
 A lista de nomes termina com um nome igual ao ponto.*/

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

char const FIM[] = ".";

int main()
{
    FILE *arq;
    char nomeS[70];
    char *ret;

    arq = fopen("arquivoGerado07.txt","w");

    puts("Insira um nome e sobrenome: ");
    ret = fgets(nomeS,sizeof(nomeS), stdin);

    while(strcmp(FIM,nomeS) != 0)
    {
        fputs(ret,arq);
        puts("Insira um nome e sobrenome: ");
        ret = fgets(nomeS,sizeof(nomeS),stdin);
    }
    fclose(arq);

    return 0;
}
    
asked by anonymous 10.10.2014 / 05:35

2 answers

1

After reading the string with fgets() remove from the '\n' .

ret = fgets(nomeS,sizeof(nomeS), stdin);
if (ret == NULL) /* erro */;
nomelen = strlen(nomeS);
if (nomelen == 0) /* erro estranho */;
if (nomeS[nomelen - 1] == '\n') {
    nomeS[--nomelen] = 0; /* remove '\n' e actualiza nomelen */
}
    
10.10.2014 / 08:25
0

According to this documentation , fgets includes the break (ie when you give Enter ) on your output - unlike gets , which does not include. So, the string read will never be equal to "." - at most it will be ".\n" , ".\r" or ".\r\n" , depending on platform ( Note ): at least this occurs when reading files - I'm not sure if stdin reading does or does not take into account the default line break of platform or if you use \n always).

For purposes of your exercise, I believe that the best way out is to use gets same, despite the danger of overflow :

ret = gets(nomeS);

In practice, however, the ideal would be either to normalize the value read or to test for the 3 variants, whichever is easiest (I have little practical experience in C, so I can not help it).

    
10.10.2014 / 07:59