在C语言中,解析多个空白的字符串分隔的整数 [英] In C, parsing a string of multiple whitespace separated integers

查看:143
本文介绍了在C语言中,解析多个空白的字符串分隔的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用C含有空格分隔的整数倍数行的文件解析成动态数组INT的动态数组。每排将阵列的阵列中的阵列。行的每一行中的元素的数量,并且是不恒定的。

I am attempting to use C to parse a file containing multiple rows of whitespace separated integers into a dynamic array of dynamic int arrays. Each row will be an array in the array of arrays. The number of rows, and elements in each row are non-constant.

什么是迄今为止我所做的是使用与fgets抓住每行一个字符串。

What I have done so far is to use fgets to grab each line as a string.

我不能,但是,弄清楚如何解析空格隔开的整数的字符串。

I cannot, however, figure out how to parse a string of whitespace separated integers.

我想我可以使用sscanf的(因为的fscanf可以用来解析空格隔开的整数的整个文件)。然而,看来sscanf的具有不同的功能。 sscanf的永远只能解析字符串中的第一个数字。我的猜测是,因为该行是一个字符串不是流。

I thought I could use sscanf (because fscanf can be used to parse a whole file of whitespace separated integers). However, it appears that sscanf has different functionality. sscanf only ever parses the first number in the string. My guess is that, because the line is a string is not a stream.

我环顾四周,一种方法,使一个流一个字符串,但它看起来不像是在C(我无法使用非标准库)可用。

I've looked around for a way to make a stream out of a string, but it doesn't look like that is available in C (I am unable to use nonstandard libraries).

char* line;
char lineBuffer[BUFFER_SIZE];
FILE *filePtr;
int value;

...

while((line = fgets(lineBuffer, BUFFER_SIZE, filePtr)) != NULL) {

    printf("%s\n", lineBuffer);

    while(sscanf(lineBuffer, "%d ", &value) > 0) {
        printf("%d\n", value);
    }
}

有什么我可以使用解析字符串。如果没有,是否有这个整个系统的方法吗?我想preFER不使用正则表达式。

Is there something that I can use to parse a string. If not, is there an alternative to this whole system? I would prefer not to use REGEX.

推荐答案

使用与strtol()< /一>它给出的指针,如果存在一个匹配的端部,和一字符指针存储当前的位置是:

Use strtol() which gives a pointer to the end of the match if there is one, and a char pointer to store the current position:

    while((line = fgets(lineBuffer, BUFFER_SIZE, filePtr)) != NULL) {

    printf("%s\n", lineBuffer);
    char* p = lineBuffer;
    while(p < lineBuffer+BUFFER_SIZE ) {
        char* end;
        long int value = strtol( p , &end , 10 );
        if( value == 0L && end == p )  //docs also suggest checking errno value
            break;

        printf("%ld\n", value);
        p = end ;
    }
}

这篇关于在C语言中,解析多个空白的字符串分隔的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆