如果填充了所有字段,我可以使用sscanf(见下文)以逗号分隔格式提取字段。但是如果字段为空,则仅填充空白字段。有什么方法可以继续,忽略空白字段的问题,以便随后的字段填充?
#include <stdio.h>
int main(int argc, char* argv[]) {
char* s = "Apple,Pear,Potato,11";
char fruit1[10];
char fruit2[10];
char vegetable[10];
int size;
int num = sscanf(s, "%20[^,],%20[^,],%20[^,],%d", fruit1, fruit2, vegetable, &size);
if (num == 4) {
printf("This record contains 4 items\n");
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
}
else {
printf("This record does not contain 4 items\n");
}
// but here it fails - blank vegetable
char* t = "Plum,Orange,,12";
num = sscanf(t, "%20[^,],%20[^,],%20[^,],%d", fruit1, fruit2, vegetable, &size);
if (num == 4) {
printf("This record contains 4 items\n");
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
}
else {
printf("This record does not contain 4 items\n");
}
return 0;
}
/*
Prints:
This record contains 4 items
first fruit: Apple, second fruit: Pear, vegetable: Potato, size = 11
This record does not contain 4 items
*/
答案 0 :(得分:0)
避免手动执行此操作,并使用strtok:
char str[] = "Apple,Pear,Potato,11";
char* tokens = strtok (str,",");
// iterate over tokens ...
while (tokens != NULL)
{
printf ("%s\n",tokens);
tokens = strtok (NULL, ",");
}
编辑:
如果您需要保留空字段,请考虑this other discussion的解决方案。
答案 1 :(得分:0)
您可以使用strchr
构建自己的扫描功能,请注意scan
会将,
替换为原始字符串中的\0
,因此如果您想要标记字符串文字(只读)你需要一个中间缓冲区:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *scan(char **pp, char c)
{
char *s = *pp, *p;
p = strchr(*pp, c);
if (p) *p++ = '\0';
*pp = p;
return s;
}
int main(void)
{
char s1[] = "Apple,Pear,Potato,11";
char s2[] = "Plum,Orange,,12";
char fruit1[10];
char fruit2[10];
char vegetable[10];
int size;
char *p;
p = s1;
strcpy(fruit1, scan(&p, ','));
strcpy(fruit2, scan(&p, ','));
strcpy(vegetable, scan(&p, ','));
size = strtol(scan(&p, ','), NULL, 10);
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
p = s2;
strcpy(fruit1, scan(&p, ','));
strcpy(fruit2, scan(&p, ','));
strcpy(vegetable, scan(&p, ','));
size = strtol(scan(&p, ','), NULL, 10);
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", fruit1, fruit2, vegetable, size);
return 0;
}
您可以使用指针简化代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *scan(char **pp, char c)
{
char *s = *pp, *p;
p = strchr(*pp, c);
if (p) *p++ = '\0';
*pp = p;
return s;
}
int main(void)
{
char s1[] = "Apple,Pear,Potato,11";
char s2[] = "Plum,Orange,,12";
char *v[4], *p;
int i;
p = s1;
for (i = 0; i < 4; i++) v[i] = scan(&p, ',');
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", v[0], v[1], v[2], atoi(v[3]));
p = s2;
for (i = 0; i < 4; i++) v[i] = scan(&p, ',');
printf("first fruit: %s, second fruit: %s, vegetable: %s, size = %d\n", v[0], v[1], v[2], atoi(v[3]));
return 0;
}