2

How can I get only the first 100 numbers(negative, integers, and floats) from a file that has numbers, spaces, and characters.

I was using this at the moment, but I think fgets is not the best command to use for this.

int readFile (FILE* fp)
{

char number[101] = "test";
//printf ("%s\n", number);
fgets(number, 101, fp);
//fscanf(fp, "%s", number);
printf ("%s", number);

return 0;
}

I suppose this current method could be used if spaces and unwanted characters were deleted, but currently this is not even working unless there are no spaces in the file.

here is an example of a file

44.5 -55 93942 11 text     text text 333.55 999999999999 1111
0x41414141
  • 364
  • 3
  • 16

3 Answers3

2

You can use fgets to get the line, then use sscanf to extract the data needed:

double d1, d6;
int i2, i3, i4, i8;
long long ll7;

sscanf(input, "%lf %d %d %d %*s %*s %*s %lf %lld %d", &d1, &i2, &i3, &i4, &d6, &ll7, &i8);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int readFile (FILE* fp){
    char buff[4096];

    while(NULL!=fgets(buff, sizeof(buff), fp)){
        char *number, *check;
        for(number=buff;NULL!=(number=strtok(number," \t\n"));number=NULL){
            //separate string by strtok, isNumber check by strtod 
            strtod(number, &check);
            if(*check=='\0'){
                printf("%s\n",number);
            }
        }
    }

    return 0;
}

int main(){
    readFile(stdin);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • This works but I don't understand the really how this is working. Would you mind explaining it more? – 0x41414141 Apr 08 '13 at 07:23
  • @bh3244 Did you see by examining the library function (strtok , strtod) ? Briefly , strtok return every call a pointer to the string that was cut in part by a delimiter string to the specified string. strtod that convert string to double, second argument (by pointer) indicates the position where it had to be able to be parsed correctly point. Indicates that the string could be interpreted as a number that the pointer to the end that points to the location of the '\ 0' is the end of the string. I may not be described well. A proper explanation, read the description of the library. – BLUEPIXY Apr 08 '13 at 08:20
0

Use fgets to parse the file contents in a single array of chars, then strtok() that for each number.
Each number you store in a double with the coresponding function. Check this out to see how you can do that.

Community
  • 1
  • 1
kundrata
  • 651
  • 3
  • 12
  • 24