gkh*_*rro 0 c file-io scanf point-in-polygon
我正在尝试使用fgets和sscanf读取多行不同长度的顶点.
(1,6),(2,6),(2,9),(1,9)
(1,5)
Run Code Online (Sandbox Code Playgroud)
我的程序进入第一个顶点内的无限循环.
char temp3[255];
while(fgets(temp3, 255, fp)!= NULL){
printf("Polygon %d: ", polycount);
while(sscanf(temp3, "(%d,%d)", &polygonx[polycount][vertcount], &polygony[polycount][vertcount]) != EOF){
sscanf(temp3, ",");
printf("(%d,%d),",polygonx[polycount][vertcount], polygony[polycount][vertcount]);
vertcount++;
}
vertcounts[polycount] = vertcount;
vertcount = 0;
polycount++;
}
Run Code Online (Sandbox Code Playgroud)
我必须能够将顶点的x和y值提供给多边形数组,所以我坚持使用sscanf.我也遇到了问题,因为我无法在互联网上找到每行扫描不同数量元素的内容.
这是因为这个
while(sscanf(temp3, "(%d,%d)",
&polygonx[polycount][vertcount], &polygony[polycount][vertcount]) != EOF)
{
}
Run Code Online (Sandbox Code Playgroud)
永远不会是true我想的,因为scanf()返回成功扫描的参数数量,我会这样做
while(sscanf(temp3, "(%d,%d)",
&polygonx[polycount][vertcount], &polygony[polycount][vertcount]) == 2)
{
}
Run Code Online (Sandbox Code Playgroud)
您的代码不起作用,因为它不满足sscanf()返回的条件EOF,以下内容来自最后引用的手册页
EOF如果在第一次成功转换或匹配失败发生之前达到输入结束,则返回该值.EOF如果发生读取错误,也会返回,在这种情况下,将设置流的错误指示符(请参阅ferror(3)参考资料),并设置errno以指示错误.
因此,如果在第一次成功转换之前输入或匹配失败发生,您似乎没有到达终点,这根据文件的内容是有意义的.第二部分当然仅适用于文件流.
而不是sscanf(temp3, ",")你没想到的那样,你可以这样做
next = strchr(temp3, ',');
if (next != NULL)
temp3 = next + 1;
else
/* you've reached the end here */
Run Code Online (Sandbox Code Playgroud)
这是关于如何解析此文件的建议
#include <stdio.h>
#include <string.h>
int
main(void)
{
const char temp3[] = "(1,6),(2,6),(2,9),(1,9)\n(1,5)";
char *source;
int x, y;
int count;
source = temp3;
while (sscanf(source, "(%d,%d)%*[^(]%n", &x, &y, &count) == 2)
{
/* this is just for code clarity */
polygonx[polycount][vertcount] = x;
polygony[polycount][vertcount] = y;
/* Process here if needed, and then advance the pointer */
source += count;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该"%n"说明符捕获已扫描的字符数,所以你可以用它来指针前进到源字符串中扫描的拉斯维加斯位置.
并且"%*[^("将跳过所有字符直到'('找到下一个字符.
sscanf(3)有关说明"%n"符和说明%[符的更多信息,请参阅.