我是编程新手,有一个小问题。
我有一个名为 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
main.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/