如何使用 c 编程语言从文件中提取一些 x 和 y 坐标,其中每行的形式为 (x1,y1) (x2, y2)?
How can some x and y coordinates be pulled out of a file where each line is in the form of (x1,y1) (x2, y2) with the c progamming language?
我需要从 .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 ) (%d ,%d )", &x1, &y1, &x2, &y2) == 4) {
printf("x1=%d, y1=%d, x2=%d, y2=%d\n", x1, y1, x2, y2);
}
return 0;
}
我需要从 .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 ) (%d ,%d )", &x1, &y1, &x2, &y2) == 4) {
printf("x1=%d, y1=%d, x2=%d, y2=%d\n", x1, y1, x2, y2);
}
return 0;
}