dimanche 29 mars 2015

How to read input from stdin until EOF read line by line with each line containing four space separated integers in C



How to read input from stdin until EOF read line by line with each line containing four space separated integers in C. It could be inputted by commands like this:


$ echo 1 2 3 4 | ./myProgram


or


$ cat file.txt

1 2 3 4

0 -3 2 -4


$ ./myProgram < file.txt

"This is where it would output my calculations"


Then I want to save the individual integers to int variables.



char strCoordinates[101];
char *ptr;
int coordinates[4];
long int tempCoordinates;
while(scanf("%s", strCoordinates) != EOF) {
tempCoordinates = strtol(strCoordinates, &ptr, 10);
int lastDigit = 0;
for (int x = 4; x >= 4; x--) {
lastDigit = tempCoordinates % 10;
coordinates[x] = lastDigit;
tempCoordinates = (tempCoordinates - lastDigit) / 10;
}
}


This is what I was trying but it seems way to complicated . . .


Any help would be greatly apprecated. Not sure whether to use scanf(), sscanf(), fscanf(), gets()




Aucun commentaire:

Enregistrer un commentaire