作业-我有一个作业要写一个程序来读取一个文件。该文件如下所示:
B 34 55 66 456 789 78 59 2 220 366 984 132 2000 65 744 566 377 905 5000
I 9000
I 389
Dm
DM其中,B是从一个数字数组构建一个二进制堆( B. i后面的数字插入到数组/堆中,Dm是最小的,DM是最大的。
我已经为堆编写了代码,并且可以用random numbers填充数组。我的问题是读取该first line并将其解析为string B和array。
我试过使用以下代码,但显然它不起作用。
char line[8];
char com[1];
int array[MAX] //MAX is pre-defined as 100
FILE* fp = fopen( "input_1.txt", "r" );
if( fp )
{
while( fgets ( line, sizeof(line), fp ) != NULL )
{
sscanf(line, "%s" "%d", &com, &array );
... //Following this, I will have a nested if that will take
each string and run the appropriate function.
if ( strcmp( com, "B" ) == 0 )
{
fill_array( array, MAX );
print_array( array, MAX );
} 在总共3天的时间里,我已经阅读了大约6个小时,无法找到解决问题的方法。任何帮助都会很好。
发布于 2012-11-30 20:53:08
首先,line数组的大小应该大于8,可能类似于char line[256]。com数组也是如此,它至少应该有3个字符。
char line[256];
char com[3];您必须使用fgets(line, sizeof(line), fp)逐行读取文件,并使用strtok()将命令与命令参数分开。
char separators[] = " ";
fgets(line, sizeof(line), fp);
char * p = strtok(line, separators); // p will be a pointer to the command string
strncpy(&com, p, sizeof(com)); // copy the command string in com
// If the command is B, read an array
if (strcmp(com, "B") == 0) {
p = strtok(NULL, separators);
while (p != NULL) {
int value_to_add_to_your_array = atoi(p);
// ... add code to add the value to your array
p = strtok(NULL, separators);
}
// ... call the function that creates your heap
}
// ... add code to handle the other commands其思想是逐行读取文件,然后对每一行首先读取命令,并根据其值确定应以何种方式读取行的其余部分。
在上面的代码中,我考虑了B命令,为此我添加了代码来读取数组。
发布于 2012-11-30 20:52:48
下面是一个小程序,它将打开一个文件,读出1行,并将发现的内容拆分到空格中:
void main()
{
char str[50];
char *ptr;
FILE * fp = fopen("hi.txt", "r");
fgets(str, 49, fp); // read 49 characters
printf("%s", str); // print what we read for fun
ptr = strtok(str, " "); // split our findings around the " "
while(ptr != NULL) // while there's more to the string
{
printf("%s\n", ptr); // print what we got
ptr = strtok(NULL, " "); // and keep splitting
}
fclose(fp);
}所以我要在一个文件上运行这个文件,其中包含:
B 34 55 66 456 789 78 59 2 220我可以预料到:
B 34 55 66 456 789 78
B
34
55
66
456
789
78我想你可以看到如何修改这个来帮助你自己。
https://stackoverflow.com/questions/13652631
复制相似问题