简体   繁体   中英

Reading strings from a file, coverting them to ints, and putting them in an array in C

I need to read an input file, use strtok to parse it, then convert the numbers to ints in an array. Right now, it's only reading the first line of of the input file and it copies the first number into the array until it hits MAX_SIZE. The count is to keep track of how many numbers are in the input file. I just need it to get to every line. Why is it only copying the first line?

718321747   -1828022042
-1665405912 -175307986
-53757018 -1551069786 525902369
-1945908378 853648883

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10

int main(int argc, char* argv[])
{
    char buffer[50];
    char* token;
    char* endptr;
    char* pointer;
    int count = 0;
    int arr[MAX_SIZE];

    if (argc != 2)
    {
        printf("Invalid number of arguments\n");
        return 0;
    }
    //open file
    FILE* fptr = fopen(argv[1], "r");
    if (fptr == NULL)
    {
        printf("Unable to open file\n");
        return 0;
    }
    //to get string line by line
    while((fgets(buffer, 50, fptr) != NULL) && (count < MAX_SIZE))
    {
        pointer = buffer;
        //to parse line
        while(((token = strtok(buffer, "\n\t ")) != NULL) && (count < MAX_SIZE))
        {
            //to convert token to int
            arr[count] = strtol(token, &endptr, 10);
            printf("%d\n", arr[count]);
            if (*endptr != '\0')
            {
                printf("Could not convert %s to integer\n", token);
            }
            else count++;
            pointer = NULL;
        }
    }
    fclose(fptr);
}

/*Sample output
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
-722170550
*/

change

while(((token = strtok(buffer, "\n\t ")) != NULL) && (count < MAX_SIZE))

to

while(((token = strtok(pointer, "\n\t ")) != NULL) && (count < MAX_SIZE))

You had forgotten to replace buffer to pointer .

This is the solution

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10

int main(int argc, char* argv[])
{
    int count = 0;
    int arr[MAX_SIZE];
    int value;

    if (argc != 2)
    {
        printf("Invalid number of arguments\n");
        return 0;
    }
    //open file
    FILE* fptr = fopen(argv[1], "r");
    if (fptr == NULL)
    {
        printf("Unable to open file\n");
        return 0;
    }

    //to get string line by line
    while ((fscanf(fptr, "%d", &value) == 1) && (count < MAX_SIZE))
        arr[count++] = value;
    fclose(fptr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM