Thread: A program that reads the number of digits in a file?

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    1

    A program that reads the number of digits in a file?

    Hello. I've been working on a program that displays the number of digits in each line of a file, but I feel stuck. Take for example a file that contains these characters:

    6347aaa9
    54j
    811111
    6a
    709

    And I'm trying to display a result like this

    1 //that's the number of the line 5 //the number of digits
    2 2
    3 6
    4 1
    5 3

    Here's what I've written so far:
    Code:
    #include<stdio.h>
    
    
    int main()
    {
        char a=0;
        int number_of_digits=0, linescount=0, num, number_of_digits_per_line=0; 
        FILE *inputFile;
    
    
        if(!(inputFile=fopen("C:\\Test\\Test.txt","r")))
        {
            printf("the file does not exist\n");
            return 0;
        }
        else
        {    
                while(!feof(inputFile))
                {
                    do
                    {
                        num=fgetc(inputFile);
                        if(isdigit(num))
                            number_of_digits_per_line++;
                            linescount++;
                            printf("%d %d\n", linescount, number_of_digits_per_line);
                    }while(a=fgetc(inputFile)=='\n');
                }
        }
        fclose(inputFile); 
    }
    I also thought of using fgets and strlen but I am not very good with them and couldn't get the program to work correctly. It did work but it displayed all characters, letters included, not only digits.
    Can you help me identify my mistake in my code and help me correct it if possible?

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    FAQ > Why it's bad to use feof() to control a loop - Cprogramming.com

    Your line count increment and message (lines 24 and 25) should be outside of that inner loop. You don't want to increment the line counter until after you finish a line.

    Also, you need to be more savvy with your logic. You read a character from the file on line 22, then read another one to test for a newline on line 27.

    Try coming up with an algorithm by hand, on paper, before writing out the code.

    Perhaps something along the lines of:

    Code:
     - read character
     - read fail?
        - file done
     - read newline?
        - increment line counter
     - read digit?
        - increment digit count

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    First, compile with warnings turned all the way up:
    Code:
    $ gcc -Wall -ggdb3 -pedantic -std=c99 -O0 -o foo foo.c -lm -lpthread -lrt
    foo.c: In function ‘main’:
    foo.c:23:21: warning: implicit declaration of function ‘isdigit’ [-Wimplicit-function-declaration]
    foo.c:27:17: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    foo.c:7:9: warning: unused variable ‘number_of_digits’ [-Wunused-variable]
    Second, read this link: FAQ > Why it's bad to use feof() to control a loop - Cprogramming.com. You'll read the last thing twice (i.e. read the last char twice since you're using fgetc. this error with fgets would repeat the last line). You should use the return value of your read functions to control the loop.

    Third, you need to #include <ctype.h> if you want to use isdigit().

    Fourth, C is not python. Indentation will not make code part of an if or loop, or anything else. Use curly braces if you want to include several statements in a sub-block. Note, the below code shows correct syntax, but the logic here is still broken.
    Code:
     if(isdigit(num)) {
        number_of_digits_per_line++;
        linescount++;
        printf("%d %d\n", linescount, number_of_digits_per_line);
    }
    Fifth, pay attention to operator precedence. The following line sets a to the result of the boolean == comparison. Once again, the below demonstrates the syntax you want, but has incorrect logic.
    Code:
    a = fgetc(inputFile) == '\n'
    // is equivalent to
    a = (fgetc(inputFile) == '\n')
    // but you really want
    (a = fgetc(inputFile)) == '\n')
    Sixth, check the documentation for functions you use. fgetc returns an int, so it can return all possible char values, plus status values like EOF. a should be declared an int, if you want it to contain the return value from fgetc.

    Seventh, you need to think carefully about what you are doing. Work out the problem, with paper and pencil, in your native language. If you can't solve the problem yourself, you can't program a computer to do it for you. You must understand the problem and solution before you begin coding. Some questions to consider:

    • When should you increase number_of_digits_per_line?
    • What should you do to number_of_digits_per_line when you start a new line?
    • When should you increase linescount?
    • When should you print linescount and number_of_digits_per_line?
    • What should the program do if a line contains no digits? Should it print <line number> 0, or should it skip output for that line?


    Lastly, implement the code. Work in small chunks, around 5 lines at a time. Compile, at maximum error/warning levels, and fix all errors. Then test your code and make sure it does exactly what it's supposed to do. Don't move onto the next section until you're completely done and error-free with the current section. The "chunks" I would have broken this program into are:

    1. Code to open and close the file. Test that it correctly handles errors with fopen. Hint, I would use perror() to print an error, it tells you why the function failed, which is very helpful when debugging.
    2. Read the file line-by-line, and count lines. Each time you read a line, print the line count and the actual line, to make sure you read the right number of lines and read whole line (no more, no less) correctly. This would catch your while (!feof) error with the double-last-line.
    3. Go through each char in the line you read, counting the digits. Each time you find a digit, print the current digit count for that line, the digit you found, and possible the position in the line you found it at, to help you verify your code is working correctly.
    4. Remove any debugging output, and add the actual output the program expects (i.e. list of lines with digit counts for that line).


    My personal preference would be to use fgets to read a whole line at a time into a buffer, then loop through the buffer counting digits. It saves you from having to worry about the logic to detect a '\n', it's built into fgets.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c++ program-the number of common digits of 2 numbers a & b
    By Sky_Daughter in forum C++ Programming
    Replies: 3
    Last Post: 12-22-2011, 05:03 PM
  2. program that reads text from a file and encodes the file by.....
    By kendrakay2000 in forum C++ Programming
    Replies: 5
    Last Post: 12-05-2010, 06:06 PM
  3. Replies: 6
    Last Post: 02-19-2009, 07:19 PM
  4. Replies: 7
    Last Post: 05-26-2003, 05:44 PM
  5. A program which reads the first characters in a file
    By Zewu in forum C++ Programming
    Replies: 2
    Last Post: 03-19-2002, 03:24 PM