本文介绍了读取C语言中的一行并将其拆分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试将'str'拆分为2个int vars和1个char var时遇到问题.这是代码:
I got a problem trying to split 'str' in 2 int vars and 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);
这是一个错误:
感谢您的帮助.
推荐答案
sscanf()仅适用于以C 0终止的标准字符串. fread()不会在读取的内容后附加0.如果要读取8个字节并使用sscanf(),则需要先0终止数据.因此,您的数组必须至少有9个字节大,以便可以将0附加到数据上.
sscanf() works only on standard C 0-terminated strings. fread() does not append a 0 to what it reads. If you want to read 8 bytes and use sscanf() you need to 0-terminate the data first. So your array needs to be at least 9 bytes big, so you can append a 0 to the data.
还需要将变量地址传递给它,以便它可以写入变量.
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);
这篇关于读取C语言中的一行并将其拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!