c - Read in of a specific amount of variables -
i have read in different coordinates , save them struct. task can use
#include <stdio.h> #include <stdbool.h>
and scanf
read in. have use gcc compiler. 1 struct need 4 coordinates, insert can this:
coordinates: 11 12 13 14 21 22 23 24 // | first | | second |
for read in have following structure:
int read() { int a; scanf("%d",&a); return a; }
main:
printf("coordinates: "); int buffer = read(); while(buffer != 0) { //write current buffer in struct ... buffer = read(); }
so problem is, structure insert needs end 0
. task is, read in procedure ends when there no more "foursome pack" of coordinates. example:
coordinates: 11 12 13 14 21 22 23 24 31 // | first | | second | invalid -> while loop ends
so dont know how cancel while loop, because dont know how coordinates user feed in.
permissible library functionalities: scanf(), printf(), putchar()
.
i hope of understand me , can me.
op's code fails distinguish between read "0"
, encountering error. not keep track of reading how many of 4 numbers read. not detect prefix "coordinates:"
int read() { int a; scanf("%d",&a); return a; }
read in "fourpack", 1 fourpack @ time.
struct pt4 { int i[4]; }; // return eof, 0, 1, or 4 struct pt *read_foursome(struct pt4 *fourpack, int count) { // prefix if (count == 0) { // record number of characters read int n = 0; if (scanf(" coordinates:%n", &n) == eof) return eof; if (n == 0) return 1; // unexpected data, prefix not there. } // record number of fields successful scanned. int n = scanf("%d%d%d%d", &fourpack.i[0], &fourpack.i[1], &fourpack.i[2], &fourpack.i[3]); // no more data if (n == eof) return eof; // no numeric data if (n == 0) return 0; // unexpected data if (n != 4) return 1; // expected return 4; }
sample usage
int n; int count = 0; struct pt4 fourpack; printf("coordinates:"); while ((n = read_foursome(&fourpack, count)) == 4) { // use fourpack printf(" %d %d %d %d", fourpack.i[0], fourpack.i[1], fourpack.i[2], fourpack.i[3]); count++; } printf("\n"); // if n == 0 maybe time line of fourpack // if n == 1, syntax error in line.
Comments
Post a Comment