0

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()

Arun A S
  • 6,421
  • 4
  • 29
  • 43
joshuatvernon
  • 1,530
  • 2
  • 23
  • 45

1 Answers1

2

Examples of One way

char strCoordinates[101];
char *ptr;
int coordinates[4];
while(fgets(strCoordinates, sizeof(strCoordinates), stdin) != NULL) {
    char *s = strCoordinates;
    for (int x = 0; x < 4; x++) {
        coordinates[x] = strtol(s, &ptr, 10);
        s = ptr;
    }
    printf("%d,%d,%d,%d\n", coordinates[0],coordinates[1],coordinates[2],coordinates[3]);
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • Why use `&ptr` rather than `&s`? And if you do want `ptr`, why not make it local to the `for` loop? – The Archetypal Paul Mar 29 '15 at 09:41
  • @Paul 1) Probably not be a problem, but two pointers is `restrict`. `long strtol( const char * restrict nptr, char ** restrict endptr, int base);`. 2) Not mean much. Because it is part of the code impact on the other is small is to define most recently to use a variable that I have added. – BLUEPIXY Mar 29 '15 at 10:06
  • 1
    Those restricts just say that nptr and endptr don't point to the same array. Since &s definitely not in the same array as the string s points to, that's OK even if you do pass &s – The Archetypal Paul Mar 29 '15 at 15:31