Read a string from a file with space

1
Hello, I want to read a file line and then return the number of spaces as well, but first I'm trying to return the entire string but when I enter a space the rest of the string is not displayed after that.

void LerArquivo()
{
FILE *fp;
char  string2[100];
int i=0,size;

   fp=fopen("PoxaProfessor.txt","r+");
   if(fp==NULL)
   {
       printf("Arquivo nao pode ser aberto");
   }


   fscanf(fp,"%s",string2);
   size=strlen(string2);
   printf("%s",string2);

   printf("\nNumeros de Caracteres: %d",size);
   printf("\nCincos Primeiros Caracteres: ");
   while(i<5)
   {
    printf("%c",string2[i]);
    i++;
   }

   fclose(fp);

}
    
asked by anonymous 01.11.2018 / 01:41

1 answer

2

You're using fscanf to read and passing "% s" as a parameter, what does that mean? You are reading a word from the last file in fscanf. How to solve this? Using functions to read an entire line, such as: fgets ( link ) or by modifying its parameter in scanf to "% [^ \ n] s "which means" read until you find a \ n ".

Your code with the fix:

void LerArquivo()
{
FILE *fp;
char  string2[100];
int i=0,size;

   fp=fopen("PoxaProfessor.txt","r+");
   if(fp==NULL)
   {
       printf("Arquivo nao pode ser aberto");
   }


   fscanf(fp,"%[^\n]s",string2);
   size=strlen(string2);
   printf("%s",string2);

   printf("\nNumeros de Caracteres: %d",size);
   printf("\nCincos Primeiros Caracteres: ");
   while(i<5)
   {
    printf("%c",string2[i]);
    i++;
   }

   fclose(fp);

}
    
01.11.2018 / 02:03