Chelpneeded
Chelpneeded

Reputation: 11

Scanf while loop affecting the next scanf outside of the loop

My test input is

[1,2,3]
[4,5,6]
[7,8,9]
[9,9]

Or it could be any number of 3d coordinates before a single 2d coordinate, my code is

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include <string.h>


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


    while(scanf("[%d,%d,%d]\n", &x1,&y1,&z1) == 3){
        printf("(x,y,z) --->  (%d,%d,%d)\n", x1,y1,z1);
    }



    scanf("[%d,%d]", &x2, &y2);
    printf("(%d,%d)\n", x2, y2);

    return 0;
}

If I change the while loop to three separate scanfs then it works fine, but the problem is that I don't know how many I will need. Is there anyway to fix this so the 2d coordinate gets scanned?

Any help would be really appreciated

Upvotes: 1

Views: 41

Answers (1)

user3121023
user3121023

Reputation: 8286

Consider using fgets to capture input. sscanf is one means to parse the input.
An advantage is the input may be parsed multiple times and the input stream is cleared up to the trailing newline.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( void){
    char line[256] = "";
    int x1;
    int y1;
    int z1;
    int x2;
    int y2;

    while( fgets ( line, sizeof line, stdin)) {
        if ( 3 == sscanf ( line, "[%d,%d,%d]", &x1, &y1, &z1)) {
            printf ( "(x,y,z) --->  (%d,%d,%d)\n", x1,y1,z1);
        }
        else if ( 2 == sscanf ( line, "[%d,%d]", &x2, &y2)) {
            printf ( "(x,y) --->  (%d,%d)\n", x2, y2);
            break;//exit the while loop
        }
        else {
            printf ( "input coordinates [x,y,z] or [x,y]\n");
            printf ( "try again\n");
        }
    }

Upvotes: 1

Related Questions