1

I'm a beginner for programming still a student. I tried to create a .txt file in C to write data, save it and after to read what I have written. And I did, it running smoothly in integer format, but when I tried to use characters (sentences), when I use spaces in my input eg:- Hi, My Name is Dilan.... It's only print Hi

I tried to using different variables in both input and output codes but still getting same result.

This Is Data Writing Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
      char txt[400];
      FILE *fptr;
      fptr = fopen("D:\\program.txt","w");
      if(fptr == NULL)
      {
      printf("Error!");
      exit(1);
      }
     printf(" Start Typing : ");
     scanf("%s",&txt);
     fprintf(fptr,"%s",&txt);
     fclose(fptr);
     return 0;
}

This Is Data Reading Code

#include <stdio.h>
#include <stdlib.h>
int main()
{
   char txt[400];
   FILE *fptr;
   if ((fptr = fopen("D:\\program.txt","r")) == NULL){
       printf("Error! opening file");
       exit(1);
   }
   fscanf(fptr,"%s", &txt);
   printf("You Have Entered :- %s", txt);`enter code here`
   fclose(fptr);

   return 0;
}

I need when I type "Hi, My Name is Dilan ...." instead of just "Hi" I need full sentence like "Hi, My Name is Dilan ...."

2 Answers2

1

Try to use fgets(txt, 400, stdin) instead of scanf("%s", &txt)

Yoni Melki
  • 205
  • 3
  • 16
0

What are you tiping in console or something else input stream is saved in a buffer("string") in operation system, your C program acces this buffer, so when you call scanf it read from that buffer, your problem is because you use %s data specificator, which read a string while the character readed is different of blank space(space, newline or tab), up to blank spaces.

After "Hi," is a space so the read will stop. You can use a different functions, one for string pourpouses, like fgets which read up to a newline character ('/n') or up to end of stream, or something else, you can search the best choice for your problem on internet.

One other solution is to use scanf repetitive to read all string, but you have to put the spaces between words in your output file.

Very important what you should have in mind all time, the functions which read from stdin stream use this buffer of OS, after one read(one execution of function) when you call again the function it will continue where it stoped in last execution, same for other streams (a file is a stream too).

In your example after you typed "Hi, my name is Xtx." In OS's buffer will be store all string. The first call o scanf will get only "Hi," the second call will get "my" and same the following calls. The problem is when you type something else in stream, like a new sentence, it will be store in buffer at end of it. So maybe your calls are still read from old string while remained unread characters in buffer from last sentence. This problem is solved with fflush(), which clean this buffer.

Xtx
  • 83
  • 10