从文件中读取字符串,将它们转换为int,然后将它们放入C中的数组中

时间:2015-01-27 02:05:44

标签: c arrays strtok

我需要读取一个输入文件,使用strtok解析它,然后将数字转换为数组中的int。现在,它只读取输入文件的第一行,并将第一个数字复制到数组中,直到达到MAX_SIZE。计数是跟踪输入文件中的数量。我只是需要它来到每一行。为什么只复制第一行?

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
*/

2 个答案:

答案 0 :(得分:1)

更改

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

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

您忘记将buffer替换为pointer

答案 1 :(得分:0)

这是解决方案

#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);
}