比如:
guangming school (grade six)
class 1 age 15 16 15 15 ...
class 2 age 14 14 15 15 ...
...要求把 age 后面的数据记录下来到一个二维数组中,应该用什么函数最简单?大概代码如何?
字符截取函数 函数名: strtok
功 能: 查找由在第二个串中指定的分界符分隔开的单词
用 法: char *strtok(char *str1, char *str2);
程序例:
#include <string.h>
#include <stdio.h>
int main(void)
{
char input[16] = "abc,d";
char *p;
/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ",");
if (p) printf("%s\n", p);
/* A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token */
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
return 0;
}
函数第一次调用需设置两个参数,strtok(str,",") str需要分割的串 “,”根据,分割
第一次分割的结果,返回串中第一个,之前的字串,也就是上面的程序第一次输出abc
第二次调用该函数strtok(NULL,"."),第一个参数设置为NULL,第二个参数还是分割的依据
结果返回分割依据后面的字串,即上面的程序输出d
功 能: 查找由在第二个串中指定的分界符分隔开的单词
用 法: char *strtok(char *str1, char *str2);
程序例:
#include <string.h>
#include <stdio.h>
int main(void)
{
char input[16] = "abc,d";
char *p;
/* strtok places a NULL terminator
in front of the token, if found */
p = strtok(input, ",");
if (p) printf("%s\n", p);
/* A second call to strtok using a NULL
as the first parameter returns a pointer
to the character following the token */
p = strtok(NULL, ",");
if (p) printf("%s\n", p);
return 0;
}
函数第一次调用需设置两个参数,strtok(str,",") str需要分割的串 “,”根据,分割
第一次分割的结果,返回串中第一个,之前的字串,也就是上面的程序第一次输出abc
第二次调用该函数strtok(NULL,"."),第一个参数设置为NULL,第二个参数还是分割的依据
结果返回分割依据后面的字串,即上面的程序输出d
温馨提示:答案为网友推荐,仅供参考
第1个回答 2011-08-30
如果格式一样的话用fscanf最简单、
伪代码:
int dummy;
fscanf(fp, "class %d age %d %d %d %d", dummy, dummy, dummy, dummy, dummy);追问
伪代码:
int dummy;
fscanf(fp, "class %d age %d %d %d %d", dummy, dummy, dummy, dummy, dummy);追问
我编了一个,没有error但不能运行,提示
debug assertion failed
file :fscanf.c
line:54
stream!=NULL但是源代码文件夹有该文本文件的
FILE *fp;
fp = fopen("where?", "r");
int num, num1, num2, num3, num4;
fscanf(fp, "class %d age %d %d %d %d", num, num1, num2, num3, num4);
fclose(fp)
谢谢,应经解决了~
又:如果数据小数很多位,需要double来定义的话,那后面应该是fscanf(fp,"class%?...)是%f还是%lf还是什么呢?
%lf
不过之前一定要用一下、否则有可能出问题、
比如double i;
i = 0.0;
第2个回答 2011-08-30
先定位fseek,然后读fread,当然传入fread的参数是一个二维数组,例如:data[0][0]追问
就这个例子而言,伪代码是什么呢,谢谢~