title: C: writing/reading files using do while loop
body: <p>I'm writing a simple exercise app in C, which should ask user if he want write something to file or read the file. I want give name to the file and then input some text in console. I want use that text to save it to the file. </p>
  
  <p>The problem is that, when I already give name to the file, I can't input data to the console and by this I can't save these datas to the text file. In addition, the while loop ignores my 'y' to restart the program again. Furthermore, when I want use reading file then it really does, program works, but it also adds instruction from default (printing just error) but I don't want that, just only read from file and print it to the console.</p>
  
  <p>Can someone explain me what I'm doing wrong and how to solve this? I'd be grateful. </p>
  
  <p>Here's my code:</p>
  
  <pre><code>int main()
  {
  FILE *file;
  char nameFile[32];
  char string[500];
  char ans[2];
  int choice;
  
  do{
      printf("What do you want to do?\n");
      printf("1. Write text to file\n");
      printf("2. Read text file\n");
      scanf("%d", &amp;choice);
      switch (choice) {
          case 1:
              printf("Give name to the file (*.txt).\n");
              scanf("%s", nameFile); //This line skips me to line where program ask user if restart the program (I have no idea why :()
              system("clear");
              file=fopen(nameFile, "w");
              if(file!=NULL){
                  printf("Input text:\n");
                  scanf("%[^\n]", string); //&lt;--- HERE I'cant input text to console, seems like scanf doesn't work.
                  fprintf(file, "%s", string);
                  printf("\n\t\t\t-----------Ended writing.------------\n");
                  fclose(file);
              }
              else
              {
                  printf("Could not open the file.");
                  return -1;
              }
              break;
          case 2:
              printf("Give name to the file (*.txt)");
              scanf("%s", nameFile);
              system("clear");
              file=fopen(nameFile, "r");
              if(file!=NULL){
                  while (!feof(file)) {
                      fscanf(file, "%s", string);
                      printf("%s\n",string); //After printing data from text file, adds instruction from line , and that is printing Error. How to get rid of it?
                  }
              }
              else{
                  printf("Could not open the file.");
                  return -1;
              }
          default:
              printf("Error.");
              break;
      }
      printf("Do you want to restart the program? (y/*)"); //Even if I write 'y', program ends anyway :(
      scanf("%s", ans);
  }
  while(ans=='y');
  return 0;
  }
  </code></pre>
  
  <p><a href="https://ideone.com/aCYJR5" rel="nofollow noreferrer">https://ideone.com/aCYJR5</a></p>