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

查看:27
本文介绍了在 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
", lineBuffer);

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

有什么东西可以用来解析字符串.如果没有,是否有替代整个系统的方法?我不想使用正则表达式.

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
", 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
", value);
        p = end ;
    }
}

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

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