我想分割一個字符串每X個字符,然後將每行存儲在一個結構數組中。但是,我想知道這將是一個簡短有效的方法。我想也許我可以使用sscanf
,但不是很確定如何。任何幫助將不勝感激。到目前爲止,我有:C - 拆分/存儲字符串的X長度到結構數組
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st {char *str;};
int main()
{
struct st **mystruct;
char tmp[] = "For configuration options (arch/xxx/config.in, and all the Config.in files),somewhat different indentation is used.";
size_t max = 20, j = 0; // max length of string
size_t alloc = strlen(tmp)/max + 1;
mystruct = malloc(alloc * sizeof *mystruct);
for (j = 0; j < alloc; j++)
mystruct[j] = malloc(sizeof *mystruct[j]);
const char *ptr = tmp;
char field [ max ];
int n;
while (*ptr != '\0') {
int line = sscanf(ptr, "%s", field, &n); // not sure how to use max in here
mystruct[j]->str = field;
field[0]='\0';
if (line == 1)
ptr += n;
if (n != max)
break;
++ptr;
++j;
}
return 0;
}
所以,當我遍歷我的結構,我能得到這樣的:
For configuration op
tions (arch/xxx/conf
ig.in, and all the C
onfig.in files),some
what different inden
tation is used.
當你說使用strncpy時,你能詳細說一點嗎?謝謝 – demit1501 2010-11-12 20:21:33