PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

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

 October 31, 2022     c, eof, input, stdin, unix     No comments   

Issue

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


Solution

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]);
}


Answered By - BLUEPIXY
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing