简体   繁体   English

Fscanf from.txt 在 C

[英]Fscanf from .txt in C

I have to scanf eg this line of text from .txt file (upload is correct):我必须从.txt文件中scanf例如这行文本(上传正确):

[1,1] v=5 s=4#o`

And this is my code:这是我的代码:

typedef struct {
    int red2[10];
    int stupac2[10];
    int visina[10];
    int sirina[10];
    char boja[10];

} Tunel;
FILE *fin = fopen("farbanje.txt", "r");
Tunel *tuneli = (Tunel *)malloc(sizeof(Tunel) * 200);

int p = 0;

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2, tuneli[p].stupac2) == 2)
{
    printf("%d %d", tuneli[p].red2, tuneli[p].stupac2);
    p++;
}

I wanted to check only 2 parameters from .txt but it gives me some random values.我只想检查.txt中的 2 个参数,但它给了我一些随机值。

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2, tuneli[p].stupac2) == 2)

Is wrong, the member variables of the struct are arrays and you need to pass them to scanf as such, for example:错了,结构的成员变量是 arrays ,您需要将它们传递给scanf ,例如:

while (fscanf(fin, " [%d,%d]", &tuneli[p].red2[0], &tuneli[p].stupac2[0]) == 2)

Or make the member variables single int s.或将成员变量设为单个int

The same with printf :printf相同:

printf("%d %d", tuneli[p].red2[0], tuneli[p].stupac2[0]);

Live demo现场演示

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

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