Read a string from a File with space

Asked

Viewed 41 times

1

Hello, I want to read a file line and then returns the number of spaces too, but first I’m trying to return the entire string but when I enter a space is not displayed the rest of the string 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);

}

1 answer

2


You are using fscanf for reading and passing "%s" as parameter, what does that mean? You are reading a word from the file passed in fscanf. How to solve this? Using functions to read an entire line, such as: fgets (http://www.cplusplus.com/reference/cstdio/fgets/) or by changing your scanf parameter to "%[ n]s" which means "read until you find an n".

Your code with the correction:

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);

}
  • if I save a string like "xx dd rr" it keeps only returning xx and ignoring the rest of the string

  • I have attached your corrected code in my reply. I have tested it here and it is working with the entry "xx dd rr" in the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.