I can’t keep the string

Asked

Viewed 159 times

-1

void ex51(char *nome_ficheiro){//escrever e criar um ficheiro novo.
  char frase[100]; 
  printf("Introduza o texto que quer escrever neste ficheiro:\n"); 
  scanf("%s",frase);
  FILE *fp=fopen(nome_ficheiro,"w");
  if(fp==NULL){
      printf("Error!!!\n");
  }else{ 
      fprintf(fp,"%s",frase); 
  }
 fclose(fp);
}

Whenever I give space or enter it only keeps the first word, I tried to use gets() to solve the problem, but gets() doesn’t work, causes the program to end soon.

2 answers

4


The scanf has a format for reading characters, so it reads everything typed up to a specific value.

scanf("%[^\n]", var); // irá ler tudo que estiver antes do \n (quebra de linha)

As his String has a fixed size, you can use a constant to indicate the maximum size you want to read.

scanf("%100[^\n], var); // irá ler os antes de \n com um limite de 100

Or you can directly read the characters, but do not recommend.

scanf("%100c", var); // lê os caracteres até um limite de 100

void ex51(char *nome_ficheiro){
  char frase[100]; 
  printf("Introduza o texto que quer escrever neste ficheiro:\n"); 

  scanf("%100[^\n]",frase); // faz a leitura da linha

  FILE *fp=fopen(nome_ficheiro,"w");
  if(fp==NULL){
      printf("Error!!!\n");
  }else{ 
      fprintf(fp,"%s",frase); 
  }
 fclose(fp);
}

Example

  • It didn’t work, keep saving only until I give a space or enter. (i.e., save a character or a word)

  • @ppfernandes, I left a link at the end of the code with the example working, a look and compare with your code, it may be that there is some logic error in it.

2

Use fgets to read a line. Do not use gets, is grounds for dismissal for just cause.

#include <stdio.h>

void ex51(char *nome_ficheiro)
{
   char frase[100];
   printf("Introduza o texto que quer escrever neste ficheiro:\n"); 

   if (fgets(frase, 100, stdin) == NULL)
   {
      printf("erro,nao foi possivel ler o texto");
     return;
   }

   FILE* fp=fopen(nome_ficheiro,"w");
   if (fp == NULL)
   {
      printf("Error!!!\n");
   }
   else
   {
      fprintf(fp,"%s",frase);
   }

   fclose(fp);
}

int main()
{
   ex51("xxx");
}
  • fgets() causes the program not to read the text (as no gets()) to simply skip, but I will try to edit the program in order to take the limit, and then I will use fgets() to see if it already gives.

Browser other questions tagged

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