-2

Hi i have this text document Now i want to store only the numbers in an array how can i do it in c language??

www.google.com *** 64
www.victoria.org **** 118
www.example.org *** 120
Paky100
  • 13
  • 2

2 Answers2

1

This should do it:

#include <stdio.h>

// read in up to 10 lines
int LINES[10];

int main(){
    int current = 0;

    // open file for reading
    FILE* file;
    file = fopen("file.txt", "r");

    // read whole file one char at a time
    while (1){
        char ch;
        if(!fread(&ch, 1, 1, file)){
            break;
        }

        if (ch >= '0' && ch <= '9'){
            int val = ch - '0';

            LINES[current] *= 10;
            LINES[current] += val;
        }else if (ch == '\n'){
            current += 1;
        }
    }


    // Looping over the results
    for (int i = 0; i <= current; i += 1){
        printf("Line %d = %d\n", i, LINES[i]);
    }
}
Phil Poore
  • 2,086
  • 19
  • 30
0

There are multiple ways you can do this.

One way is to read the numbers into a temporary char[] array one character at a time with fgetc, then convert it to an int with the use of atoi().

To test if characters are integers, you can use the isdigit function from <ctype.h>, or you can simply test ch >= '0' && ch <= '9', either way works.

Here is some sample code:

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

#define NUMLINES 10
#define NUMLEN 5

int main(void) {
    FILE *fp;
    int LINES[NUMLINES], i, count = 0, ch, blen = 0;

    /* static temp buffer, make it bigger if integers will be more than 5 digits */
    /* dynamic memory allocation always possible here */
    char buffer[NUMLEN+1];

    /* opening the file, with error checking */
    fp = fopen("urls.txt", "r");
    if (!fp) {
        fprintf(stderr, "%s\n", "Error reading file");
        return 1;
    }

   /* read each character until EOF */
    while ((ch = fgetc(fp)) != EOF) {

        /* digit found. add to temp buffer */
        if (isdigit(ch)) {
            buffer[blen++] = ch;
        }

        /* stop adding to buffer, now convert and add to array */
        if (ch == '\n') {
            buffer[blen] = '\0';
            LINES[count++] = atoi(buffer);
            blen = 0;
        }
    }

    /* print the array */
    for (i = 0; i < count; i++) {
        printf("LINES[%d] = %d\n", i, LINES[i]);
    }

    return 0;
}

Which should output:

LINES[0] = 64
LINES[1] = 118
LINES[2] = 120
RoadRunner
  • 25,803
  • 6
  • 42
  • 75