我想分割一个字符串每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