Search code examples
cfilenumbersc-stringscounting

Count the amount of numbers on each line in a text file


I am currently learning C programming (my experience is in Python, Java and Swift). I am trying to count how many numbers are on the first line of a text file.

The text file looks a bit like this:

-54 37 64 82 -98 
...

I have tried various different ideas that I have had. The first was to check each character in turn for the EOL, and if it wasn't to add 1 to the total. I quickly realised this only works for single digit numbers, and not general integers.

I then tried to use fscanf to find the last number on the line, and then rewind and use fscanf to count each number until that last number was found again:

int temp;
FILE *fd = fopen("test.txt", "r");

fscanf(fd, "%d\n", &temp);
printf("Last Number on Line is: %d\n", temp);

However before I could even write the next logic to count the numbers I realised that this printed Last Number on Line is: -54 which was not the expected output from the above file example.

At this point I am rather stuck. Searching online mainly returns results on how to count how many lines are in a file due to the similarity of the question.

Any help would be much appreciated!


Solution

  • In the end I have used the suggestion here and come up with the following solution:

    char buffer;
    int  temp = 0;
    int  row_count = 0;
    
    while((buffer = getc(fd)) != '\n') {
        if (temp == 0 && (isdigit(buffer))) {
            col_count += 1;
            temp = 1;
        } else if (temp == 1 && buffer == ' ') {
            temp = 0;
        }
    }
    

    This is working fine for me in the context I am using it within, thanks for the help