Ignitus
Ignitus

Reputation: 13

Problems with getting data from multi-line input in the from ./{base} < input.txt

I've got a problem I've tried to research it but can't really find the answer I'm looking for.

I'm trying to take in a multi-line text file in this manner in C

./{base_name} < input.txt

input.txt contains

54
37
100
123
1
54

I've got it sort of working by doing

scanf("%[^\t]",s);

but I want to get each number and parses the C-string into an integer array maybe by using atoi(). I'm pretty unsure about how to do it.

Right now my code looks like this

int main(int argc, char *argv[]){
   char str[1000];
   scanf("%[^\t]",str);
   printf("%s\n", str);
}

Is there anyway to make use of argc and **argv to do this, or another neat way of taking the input and make an int array of it.

I'm compiling with:

gcc -w --std=gnu99 -O3 -o {base_name} {file_name}.c -lm

The best thing to do would be just to take it as a .txt file and use fopen etc. but the assignment requires me to take the input as ./{base_name} < input.txt

I've got an answer that worked. Other than that I've got this piece of code which also worked quite fine. Would however recommend the accepted answer as it defines the size of the array from the input. Thanks a lot for your help.

#include <stdio.h>
int main(){
    char s[100];
    int array[100];
    while(scanf("%[^\t]",s)==1){
        printf("%s",s);
    }
    return 0;
}

Upvotes: 1

Views: 110

Answers (2)

someone
someone

Reputation: 361

You could try this code:

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

int main(int argc, char *argv) {
   FILE *file;
   int numbers[100] /* array with the numbers */, i /8 index */, j;

   if (!(file = fopen(argv[1], "r")) return -1; /* open the file name the user inputs as argument for read */

   i = 0; /* first place in the array */
   do /* read the whole file */ {
      fscanf(" %d", &(numbers[i]); /* the space in the format string discards preceding whitespace characters */
      i++; /* next position */
   }

   for (j = 0; j < i; j++) printf("%d", numbers[j]); /* print the array for the user */

   return 0;
}

Upvotes: 0

P0W
P0W

Reputation: 47824

Why not just simply read the inputs as integers ?

//test.c
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]){
   int n;
   int i;
   int *arr;

   /*Considering first value as number of elements */
   /*Else you can declare an array of fixed size */
   fscanf(stdin,"%d",&n);
   arr = malloc(sizeof(int)*n);

   for(i=0;i<n;i++)
    fscanf(stdin,"%d",&arr[i]);


   for(i=0;i<n;i++)
    printf("%d ",arr[i]);

    free(arr);
    return 0;
}

Now use :

./test < input.txt

Assumed input.txt :

6  <- no. of elements (n)
54
37
100
123
1
54

Upvotes: 1

Related Questions