Thread: New help using a counter

  1. #1
    Registered User
    Join Date
    Jun 2016
    Posts
    16

    New help using a counter

    I need help understanding why this program outputs "Count = 3" if the input file is:

    -3xy' - ay" - bcos(t) = sin(t)
    ,
    4y - 3y' = - y'

    What I intended for my counter to output was the number of characters there are in my input file. Any help is appreciated.

    Code:
    main()
    {    int count = 0;
        char z[1000];
        FILE *fin, *fout;
        fin = fopen("cp1_ODEin.txt", "r");
            if((fin = fopen("cp1_ODEin.txt", "r")) == NULL)
                printf("Failed to open cp1_ODEin.txt");
        fout = fopen("cp1_ODEout.txt", "w");
            if((fout = fopen("cp1_ODEout.txt", "w")) == NULL)
                printf("Failed to open cp1_ODEout.txt");
         
        while(fgets(z, 1000, fin) != NULL){
            fputs(z, stdout);
            count = count + 1;
        }
        printf("\nCount = %d", count);
        fclose(fin);
        fclose(fout);
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Sooo...you're reading a three line file with fgets and incrementing count on each successful call of fgets, then printing the value of count. "Count = 3" being the output seems legit to me. Note here that fgets reads more than one character (up to 998 or 999, to be specific in this case). If you want a count of characters, saving the length of the read string seems reasonable. Or if you don't care about the actual characters, only the count, try using fgetc instead of fgets.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. counter
    By Miguel Garcia in forum C Programming
    Replies: 1
    Last Post: 05-01-2015, 10:20 AM
  2. Page File counter and Private Bytes Counter
    By George2 in forum Tech Board
    Replies: 0
    Last Post: 01-31-2008, 03:17 AM
  3. The counter
    By Gordon in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 05:50 AM
  4. Help With a Counter
    By Halo in forum C++ Programming
    Replies: 3
    Last Post: 12-15-2005, 04:03 PM
  5. counter
    By Colonial Viper in forum C++ Programming
    Replies: 4
    Last Post: 04-01-2005, 11:44 AM

Tags for this Thread