微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 c 编程语言从每行格式为 (x1,y1) (x2, y2) 的文件中提取一些 x 和 y 坐标?

如何解决如何使用 c 编程语言从每行格式为 (x1,y1) (x2, y2) 的文件中提取一些 x 和 y 坐标?

我需要从 .txt 文件中的一行中提取各个点并将它们分配给已经初始化的变量。

//String would be something like (4,2) (1,5)
//I've tried to use scanf to use the keyboard and then from there I would move it over to
//fscanf and open the file.  So far I haven't been successful with scanf.  I tried this:  

int xCoord = 0;
int yCoord = 0;

printf("\nThis section grabs coords from user input\n");
printf("\n\nType in coordinates in the form of (x,y)\n");
scanf("%d %d",&xCoord,&yCoord);

printf("The x coordinate is: %d\nThe y coordinate is: %d\n",xCoord,yCoord);

//我不确定获取数字的最佳方法。如果没有,我已经能够让它工作 //使用括号。我考虑过分词器,但我只是想要一些建议。 //谢谢

解决方法

您当然可以使用 scanf()。格式字符串应为 " (%d,%d ) (%d,%d )"。格式字符串中的空格允许使用任何空格,字符 (), 与自身匹配。

这是一个测试程序:

#include <stdio.h>

int main() {
    int x1,y1,x2,y2;

    printf("\nThis section grabs coords from user input\n");
    printf("\n\nType in coordinates in the form of (x1,y2) (x2,y2):\n");
    while (scanf(" (%d,%d )",&x1,&y1,&x2,&y2) == 4) {
        printf("x1=%d,y1=%d,x2=%d,y2=%d\n",x1,y2);
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。