使用c语言拆分字符串

时间:2012-12-19 10:25:59

标签: c string split

我有一个包含以下行的文件:

0: 1(ab) 6(a)
1: 3(b) 4(a)
2: 5(a) 3(ab)

我想拆分这些行来获取值,并以某种方式将它们存储在数组或其他内容中。

任何帮助!

More Explanations

0,1,2是格拉夫的峰。

对于第一个峰值0,我们在括号中有两个弧1和6,弧的值。

1 个答案:

答案 0 :(得分:0)

fscanf似乎正常工作,因为@Adeel建议: -

#include<stdio.h>

int main()
{
    int peak, arc1, arc2;
    char v1[100], v2[100];
    scanf("%d: %d(%s %d(%s", &peak, &arc1, &v1, &arc2, &v2);
    v1[strlen(v1)-1] = 0; // clear the closing parentheses
    v2[strlen(v2)-1] = 0; // clear the closing parentheses

    printf("%d, %d, %s, %d, %s", peak, arc1, v1, arc2, v2);
}

需要清除,因为字符串读取太远了。如果输入没有任意空格,这将起作用。对于那些情况,可能需要strtok等。

经过测试: -

C:\Users\user\Desktop>test.exe
0: 1(ab) 6(a)

输出: -

0, 1, ab, 6, a
相关问题