【问题标题】:Splitting a string in a file into array in c将文件中的字符串拆分为c中的数组
【发布时间】:2015-01-03 14:52:57
【问题描述】:

我是编程新手,遇到了一个小问题。 我有一个名为questions.txt 的文件,其中包含一串问题,我想从文件中读取字符串,然后将其拆分为数组,每个问题都有一个索引,例如a[i] = "Question 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?

【问题讨论】:

  • 在您的问题中添加您的代码,我们会更容易为您提供帮助。
  • 请告诉我们您的尝试。
  • 欢迎来到 Stack Overflow。这里的人非常愿意帮助解决代码的具体问题,但他们不会给你完整的答案。请阅读How to Ask,其中除其他外,他们告诉您输入您尝试过的一些代码并提出特定问题。

标签: c string file strtok string-split


【解决方案1】:

我想从文件中读取字符串,然后将其拆分为一个数组,每个问题都有一个索引...

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

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

我可以假设您想要制作文件的向量(一维数组)。在该向量中,每个元素都将包含文件中的一个问题。对吧?

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

简而言之,这个小程序做了以下事情:

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

【讨论】:

  • @z.n14,我建议你使用我在这里发布的功能。它非常有用,您可以将它应用到您接下来的所有程序中。我几乎每次必须处理文本和文件时都使用此功能。我强烈建议在你的程序中使用它——你会看到,它会令人叹为观止。
  • 这里显示的代码似乎使用了属于 GNU C 库argz functions 的函数 - 声称:“...我可以与您分享我的库中的一个函数在大学里做的......”对我来说似乎有点不对劲...... 8-(
【解决方案2】:

我认为你想要的是这样的:

#include <stdio.h>
int main(){
int i=0;
char str[200],s='1'; //s is give a random character  

FILE * fp = fopen("questions.txt", "r");
while (s!=EOF){     //works until s= the end of file
    s=getc(fp);          //s starts to receive characters from text file
    str[i]=s;   //each character of text is placed into the string array
    i++;        
}
str[i]='\0'; //s reached EOF so lets indicate where we stopped in the string
fclose(fp);

printf("%s\n",str);

//EDIT: changing 1D str to 2D str2 
char str2[10][200]; // 10 for max no. of questions, 200 - length of each question
int j=0,k=0;
i=0;

for(j=0;j<200;j++){  
str2[i][k]=str[j];
k++;
    if (str[j]=='\n'){
    i++;
    k=0;}
}

for(i=0;i<10;i++)  //prints your 2D string array
printf("%s",str2[i]); //after the last question there will be junk
return 0;
}

【讨论】:

  • 这正是我想要的,但这不是只在索引“i”中存储字符吗?我试图在 1 个索引中得到一个完整的问题
  • 你知道说 str[10] 和 str[10][100] 的区别吗?
  • 第一个是一维数组,指向第10个元素,第二个是二维数组,指向第10列第100行的元素,对吧?
  • 如果 char a[10] = "hello" 这意味着 a[0]='h', a[1]='e', a[2]='l' ..etc *每个元素都是一个字符长。
  • 我想要类似 a[1] = "question x" 这可能吗?
猜你喜欢
  • 2022-01-18
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多