如何解决C 格式化字符串
我有这样的功能和输入
"{ \'Carl Weber Maria von\',\'weber\',2 }\n"
"{ \'Carl-Maria von Weber\',4 }\n"
"{ \'Chuck Norris\',\'norrischuck\',100 }";
它像这样创建输出:
Chuck Norris,norrischuck,100
}{
我如何确保没有像 {} 这样的字符存储在我的字段中。不知何故,我无法修改此函数以获得所需的结果。预先感谢您的回答。功能:
int fillPoints (FILE *fp,TSTUDENTLIST *l)
{
char *src;
char a[2000];
src=a;
fscanf(fp,"%[^\"]s",src);
int count=1000;
char output[1000][1000];
int i = 0;
while (i < count) {
const char *start;
int len;
while (isspace((unsigned char)*src))
src++;
if (*src == '\0')
break;
if (*src == '\'') {
start = ++src;
len = strcspn(src,"\'");
src += len;
if (*src == '\'')
src++;
} else
if (*src == '\"') {
start = ++src;
len = strcspn(src,"\"");
src += len;
if (*src == '\"')
src++;
} else {
start = src;
len = strcspn(src," \t\f\v\r\n");
src += len;
}
snprintf(output[i],sizeof(output[i]),"%.*s",len,start);
i++;
}
}
解决方法
为简单起见,我建议您在每行上进行多次传递,每次传递都会将行的一部分复制到临时数组中。
例如,如果存在分号,则删除尾随分号的初始传递(为此,您实际上不需要复制)。然后通过复制除开始和结束双引号 "
之外的所有内容。然后是大括号的一关。还有一次通过反斜杠(以及 n
中的 \n
)。以及单引号的最后一关。
所有这些都应该让您得到类似 "Chuck Norris,norrischuck,100"
的东西。并且可以将其提供给 strtok
以对逗号进行“标记化”,您只需调用它两次即可获得三个单独的字符串 "Chuck Norris"
、"norrischuck"
和 "100"
。您可以传递给 strtoul
以转换为整数的最后一个。
一旦你得到长的多通道解决方案,你当然可以将所有的通道组合成一个通道。
当我说您对输入进行“传递”时,我的意思是您遍历字符串,将除不需要的字符以外的所有字符复制到新的临时数组中。
例如:
// Previous pass puts its output in pass_1_output
// Pass to remove double-quotes
char pass_2_ouput[1000] = { 0 }; // Zero-initialize,which is the string terminator
for (size_t in = 0,out = 0; pass_1_output[in] != '\0'; ++in)
{
if (pass_1_input[in] != '"')
{
// Not a double-quote,copy the input to the output
pass_2_output[out++] = pass_1_input[i];
}
}
// After the above loop,pass_2_output will contain the same contents as
// pass_1_output,*except* any double-quotes
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。