c - 将文件中的字符串拆分为c中的数组

标签 c string file strtok split

我是编程新手,有一个小问题。 我有一个名为 questions.txt 的文件,其中包含一串问题,我想从文件中读取该字符串,然后将其拆分为数组,每个问题都有一个索引,例如 a[i ] =“问题i”等。 我做了很多尝试,但它总是最终读取文件中的最后一行,当写入循环时程序停止工作。

这是我想出的,它可能都是错误的:

char str[200];

char *ptr;
FILE * fp = fopen("questions.txt", "r");
while(fgets(str, 200, fp)!= NULL)
printf("%s", str);
ptr = strtok(str, "\n");

while(ptr != NULL)
{
    ptr = strtok(str, "\n");
    printf("%s\n", ptr);
    ptr = strtok(NULL, "\n");
}
fclose(fp);      

文件是:

what is your course?
who is your instructor?

我得到的输出是:

what is your course?
who is your instructor?
who is your instructor?

最佳答案

I want to read the string from the file then split it into an array with each question having an index...

让我说,您没有要拆分为数组的字符串。 您最好有一个包含一串问题的文件,如下所示:

what is your course?:who is your instructor?  // `:` is some kind of delimiter

我可以假设您想要创建文件的 vector (一维数组)。在该 vector 中,每个元素将包含文件中的一个问题。对吗?

我可以与您分享我在大学时制作的图书馆的一个功能。我将在这里写一个简单的程序。但它使用分隔符 - 例如,:。您可以修改此函数以使其在没有分隔符的情况下工作 - 这仅取决于您。

用两个词来说,这个小程序执行以下操作:

// BEFORE: you have a string that ends with a null terminating character.
Question_1_abcbadsad:QUestion_2asasdasd:Question_3sldasdsa\n
                                                          ^
                                                     here ^<< printing 'string' stops
// AFTER: an array of questions. Each of them ends with a null terminating character.
Question_1_abcbadsad\nQUestion_2asasdasd\nQuestion_3sldasdsa\n
                    ^
                    ^<< printing argz[0] will stop here

ma​​in.c

#include "argz.h"

int main()
{
    error_t func;     

    char *argz; // pointer to a vector; to an array of questions

    size_t argz_len;  
    // size of that vector (the size of the string you've got from the file)
    // Consider `string` to be your `ptr`. You read a string from the file so
    // `ptr` will point to the string.         

    char *string = "Question_1_abcbadsad:QUestion_2asasdasd:Question_3sldasdsa";

    // Here `:` is a separate character.
    func = argz_create_sep(string, ':', &argz, &argz_len);
    if(func == OK)
        argz_print(argz, argz_len);
    else
        printf("ERROR\n");

    return 0;
}

argz.c

#include "argz.h"

error_t argz_create_sep (const char *string, int sep, char **argz, size_t *argz_len)
{
    int i;
    char *ch;
    int len = strlen(string);

    if(len==0)
        return ENOMEM;

    *argz = (char*) malloc (sizeof(char)*(len + 1));
    strcpy(*argz, string);
    *argz_len = strlen(*argz);
    ch = *argz;
    for(i = 0; i < len; i++) {
        if(*ch == sep) *ch='\0';
        ch++;
    }
    return OK;
}


void argz_print(const char *argz, size_t argz_len)
{
    const char *ch;
    int i;

    ch = argz;
    for(i = 0; i < argz_len; i++) {
        if(*ch == '\0')
            printf("\n");
        else
            printf("%c",*ch);
        ch++;
    }
    printf("\n\n\n");
}

argz.h

#include <stddef.h> // for size_t
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef enum  {OK, ENOMEM} error_t;

/* function prototypes */
error_t  argz_create_sep (const char *string, int sep, char **argz, size_t *argz_len);
void     argz_print      (const char *argz, size_t argz_len);

关于c - 将文件中的字符串拆分为c中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756090/

相关文章:

python - 将字符串转换为字典的简单方法

c - 如何将字符串分配给位于 C 结构中的 char 数组?

c# - 通过 asp.net 传送图像的最快方式

c++ - 编译 C++ 代码时出错(无效转换)

multithreading - 使用线程读取输入时缺少字符

c - Azure IoT C SDK 中连接状态的语义

c - 打印多个整数输出 0

C 参数定义问题

c 字符指针比较

javascript - .trim() 和正则表达式产生意想不到的结果