简体   繁体   English

读取 C 中每行大括号之间的空格分隔的未知整数数量的文件

[英]Reading a file where there is an unknown number of integers separated by spaces between curly brackets per line in C

I've seen this previous post , but this one doesn't work for my situation.我已经看过this previous post ,但这一篇不适用于我的情况。

My situation is down below.我的情况在下面。

1 { 87 36 135 }
2 { 100 156 167 43 92 174 149 21 }
3 { 144 7 58 149 127 189 5 54 57 }
4 { 128 61 30 4 165 72 117 }
5 { 158 104 196 156 151 162 198 }
6 { 87 98 14 }

My goal is to put these integers between curly brackets into a 2D array.我的目标是将大括号之间的这些整数放入二维数组中。 Then, I can manipulate them.然后,我可以操纵它们。

I also tried it in the C version.我也在 C 版本中尝试过。 My idea is to go to the left curly bracket to save the number and go to the next line when it meets the right curly bracket.我的想法是将 go 到左大括号以保存数字,并将 go 到下一行,当它遇到右大括号时。 However, my idea doesn't work for the above situation because the integers my two or three characters.但是,我的想法不适用于上述情况,因为整数是两个或三个字符。

char str1;
int count = 1;
int no;
char c;
FILE *filepointer;
// filepointer = fopen("~", "r");
filepointer = fopen(argv[1], "r");
printf("\n The content of the file %s is  :\n", argv[1]);
c = fgetc(filepointer);

while (c != EOF)
{
    if(c == '{'){
        int adj = 1;// may be careful
        while (c != '}')
        {
            while (isspace(c = fgetc(filepointer)))
                ;
            if(c == '}')
                break;
            int returnNumber = 0;
            returnNumber = returnNumber * 10 + (c - '0');
            nets[count][adj] = returnNumber;
            adj++;
        }
        count++;
    }
    
    // printf("%c", c);
    c = fgetc(filepointer);
}
no = count;
printf("\n\n");
fclose(filepointer);
for (int i = 1; i < no;i++){
    for (int j = 1; j < MAX_ADJCENT_SIZE;j++){
        printf("%d ", nets[i][j]);
    }
    printf("\n");
}

Thanks for your attention.感谢您的关注。 Please help me, If some condition I do not mention.请帮助我,如果某些情况我没有提及。 plz tell me.请告诉我。 I will edit ASAP.我会尽快编辑。

You could read all characters that are digits before saving the number and moving on to the next:在保存数字并继续下一个之前,您可以读取所有数字字符:

int returnNumber = 0;

if (c >= '0' && c <= '9') {
    do {
        returnNumber = returnNumber * 10 + (c - '0');
        c = fgetc(filepointer));
    } while (c >= '0' && c <= '9');

    nets[count][adj] = returnNumber;
    adj++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM