如何使用C解析文本文件并获取所有的int

时间:2016-11-17 03:52:20

标签: c parsing text

我不是最好的C程序员,我试图解析包含单词和整数的文本文件,我试图将所有的int保存到不同的变量中。我在浏览所有其他角色时遇到了麻烦,只能获得内容

我的文本文件如下所示:

Task[0] 0, 11, 27, 53, {2, 1, 1, 0, 0, 0, 0, 0, 0, 0}, 3 Task[1] 1, 22, 49, 92, {2, 1, 2, 0, 0, 0, 0, 0, 0, 0}, 3

int x = 0;
int t;
FILE *ptr_file;
int lines = 0;
int ch = 0;
ptr_file = fopen("tasks.txt", "r");
if (!ptr_file)
    return;

int i, id, readyTime, WCET, deadline, numberOfResources;
int resources[10];

while(!feof(ptr_file))
{
  ch = fgetc(ptr_file);
  if(ch == '\n')
  {
    lines++;
  }
}
while(x < lines)
{
    //gets the whole task line
    fscanf(ptr_file, "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &t, &id, &readyTime, &WCET, &deadline, &resources[0], &resources[1], &resources[2], &resources[3], &resources[4], &resources[5], &resources[6], &resources[7], &resources[8], &resources[9], &numberOfResources);

    printf("Task %d, id %d, readytime %d, WCET %d, deadline %d, resources (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d) numResources %d\n", x, id, readyTime, WCET, deadline, resources[0], resources[1], resources[2], resources[3], resources[4], resources[5], resources[6], resources[7], resources[8], resources[9], numberOfResources);
    ++x;
}
fclose(ptr_file);

我认为我没有正确使用fscanf,但却无法使用它。

任何帮助都会很棒

1 个答案:

答案 0 :(得分:0)

也许这会有所帮助:

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

int main(void)
{
    const char *input = "Task[0] 0, 11, 27, 53, {2, 1, 1, 0, 0, 0, 0, 0, 0, 0}, 3";
    const char *it = input;
    char *next;

    while( *it )
    {
        int value = strtol( it, &next, 10 );
        if( it == next )
        {
            printf( "Text: '" );
            while( *next && !isdigit(*next) ) {
                putchar( *next );
                next++;
            }
            printf( "'\n" );
        }
        else
        {
            printf( "Value: %d\n", value );
        }
        it = next;
    }

    return 0;
}

输出:

Text: 'Task['
Value: 0
Text: '] '
Value: 0
Text: ', '
Value: 11
Text: ', '
Value: 27
Text: ', '
Value: 53
Text: ', {'
Value: 2
Text: ', '
Value: 1
Text: ', '
Value: 1
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: ', '
Value: 0
Text: '}, '
Value: 3

请注意,它不会处理负整数,但这很容易纠正。