繁体   English   中英

从文件中读取每一行,然后在C中将该行拆分为一个字符串和一个数组

[英]Read each line from a file and split the line into a string and an array in C

作业 -我分配了一个程序来读取文件。 该文件如下所示:

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后面的数字。我是在数组/堆中插入一个数字Dm是删除最小值,而DM是删除最大值。

我已经为堆编写了代码,并且可以用random numbers填充数组。 我的问题是读取first line并将其解析为string Barray

我尝试使用以下代码,但显然不起作用。

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 );
        }        

我已经阅读了大约6个小时,总共3天,但无法找到解决我问题的方法。 任何帮助都会很棒。

这是一个小程序,它将打开一个文件,读出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

我认为您可以看到如何修改此设置以帮助自己。

首先, line数组的大小可能应该大于8,可能类似于char line[256] com数组也是如此,该数组至少应包含3个字符。

char line[256];
char com[3];

您必须使用fgets(line, sizeof(line), fp)读取文件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命令,为此我添加了代码以读取数组。

暂无
暂无

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

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