简体   繁体   中英

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?

I need to extract the various points from a line in a.txt file and assign them to variables that are already initialized.

//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);

//I'm not sure the best way to get just the numbers. I have been able to get it to work if no //parenthesis are used. I've considered a tokenizer but I just wanted some suggestions. //Thanks

You certainly can use scanf() . The format string should be " (%d,%d ) (%d,%d )" . The spaces in the format string allow for any whitespace and the characters ( , ) and , match themselves.

Here is a test program:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM