问题描述
我需要从 .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;
}