简体   繁体   English

读取C中的一行并将其拆分

[英]Read a line in C and split it

I got a problem trying to split 'str' in 2 int vars and 1 char var. 我在尝试将'str'拆分为2个int var和1个char var时遇到问题。 Here is a code: 这是一个代码:

FILE *fp;
int i,j;
char str[8];
char valor;
if(!(fp = fopen("miniflota_g.dat","rb"))){
    printf("Error opening file.");
    getch();
    return;
}
while(fread(str,sizeof(str),1,fp) == 1){
    sscanf(str,"%d %d %c",i,j,valor);
    printf("%d %d %c",i,j,valor);
}
fclose(fp);

And this is an error: 这是一个错误: 在此处输入图片说明

Thanks for any help. 谢谢你的帮助。

sscanf() works only on standard C 0-terminated strings. sscanf()仅适用于以C 0终止的标准字符串。 fread() does not append a 0 to what it reads. fread()不会在读取的内容后附加0。 If you want to read 8 bytes and use sscanf() you need to 0-terminate the data first. 如果要读取8个字节并使用sscanf(),则需要先0终止数据。 So your array needs to be at least 9 bytes big, so you can append a 0 to the data. 因此,您的数组必须至少有9个字节大,因此可以在数据后附加一个0。

Also you need to pass the variable addresses to it, so it can write to them. 另外,您需要将变量地址传递给它,以便它可以写入它们。

So it should look more like this: 所以它应该看起来像这样:

FILE *fp;
int i,j;
char str[9] = { 0 };
char valor;
if(!(fp = fopen("miniflota_g.dat","rb"))){
    printf("Error opening file.");
    getch();
    return;
}
while(fread(str,sizeof(str)-1,1,fp) == 1){
    sscanf(str,"%d %d %c",&i,&j,&valor);
    printf("%d %d %c",i,j,valor);
}
fclose(fp);
  1. You never null-terminate 'str' so the sscanf could read off the end. 您永远都不能使用null终止'str',因此sscanf可以读出结尾。

  2. You need to pass to sscanf the addresses of the output variables, not the values. 您需要将输出变量的地址而不是值传递给sscanf。 (Eg. &i instead of i ). (例如, &i代替i )。

  3. If you enable compiler warnings (-Wall with gcc), your compiler will warn you about the second point, at least. 如果启用了编译器警告(带有gcc的-Wall),则编译器至少会警告您第二点。

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

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