简体   繁体   中英

I'm supposed to read a text from a .txt and display it in the console but my code is not working,where is my mistake?

Firstly, I'm asked to type a text in the console and print it in a .txt file. Then,after I've printed that text in the .txt file,I'm supposed to print that text in the console and by the end of each line to show how many characters each line have.

    ex:
    Annie is a 8
    big girl 7
    with big dreams 13 


  for  (int i=0;   i<4   ;i++)
{
    while ((c=fgetc(p))!=EOF||(c=fgetc(p))!='\n')
      {
          printf("%c",c);
          n++;
      }
      printf("%d",n);
}

This part is the problematic one. After I've input the text and print it in the .txt file, I've tried to print out character by character in the console and the "n" variable should be the counter of each letter. Where is my mistake? I can show the whole code if needed.

Please make your question clear. What does not work, is n displaying the wrong number of characters or what is your problem?

This little code sample should work if only n is displaying the wrong number:

char c = ''; //so in default it is empty

for  (int i=0;   i<4   ;i++)
{
      int n=0;
      while( (c=fgetc(p))!=EOF && c!='\n')
      {
          printf("%c",c);
          if(c!=' ')//so we only count the letters and not whitespaces
              n++;
      }
      printf("%d",n);
}

This should give your desired result when your file opening part works.

Didn't you forget rewind (or fseek) instruction ? If you write the .txt file and after you try to read it without rewind (or fseek or close/fopen) instruction, the file position is at the end of the file. So there is not char to read because you are already at the end of file. Try the following code with and without the rewind instruction.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char c = '\0';
    int n;

    FILE * p;
    p=fopen("myfile.txt","w+");
    fprintf(p,"Annie is a\nbig girl\nwith big dreams");

    rewind(p);

    while((c=fgetc(p))!=EOF) {
        if (c=='\n') {
            printf(" : %d\n",n);
            n=0; }
        else {
            printf("%c",c);
            if (!isspace(c)) n++;
        }
    }
    printf(" : %d\n",n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM