1

I have this snippet:

printf("\nEnter number of elements: ", MAX);
scanf("%d", &num);
printf("\nEnter %d Elements : ", num);
for (i = 0; i < num; i++)
  scanf("%d", &arr[i]);

I want to enter say, 1000 integers to the arr[i] but how do I do it without entering 1000 numbers manually? I was thinking of using an external file to store the numbers and I just read it there but I don't know how to...

Achal
  • 11,821
  • 2
  • 15
  • 37
neumear
  • 111
  • 10
  • Looks like you are more interested in C than C++. Sticking with C, don't forget to check the return value from `scanf` to make sure you actually read something. [Also look into `fscanf` to read from files.](http://en.cppreference.com/w/cpp/io/c/fscanf) – user4581301 Mar 25 '18 at 05:29
  • I'm flexible, I alternatively use C and C++ – neumear Mar 25 '18 at 05:30
  • In C++, [you would use a `std::ifstream`](http://en.cppreference.com/w/cpp/io/basic_ifstream) pretty much the same way you would `std::cin` – user4581301 Mar 25 '18 at 05:32
  • Input redirection, e.g. `./myprogram – user3386109 Mar 25 '18 at 05:33

1 Answers1

2

There are two simple approaches: First, you can use a file of numbers:

printf("\nEnter number of elements: ", MAX);
scanf("%d", &num);

FILE *f = fopen("numbers.txt","r");
if (f == NULL){... handle error }
for (i = 0; i < num; i++)  
  fscanf(f,"%d", &arr[i]);
fclose(f);

This is fine, but you should, of course, test fscanf for errors (see the documentation of fscanf) and at the same time, you can replace num with waiting for feof(f) signaling the end of file.

Still, on most operating systems, there are shell pipes that can actually make a file an input to a program. For your snippet, you could format your file by placing the number of numbers in the first line and then the input to the second round of scanfs (e.g., the space separated numbers) into the second line.

Then, on Linux, cat filename.txt | yourprogram will behave as if you were inputting the content of file through the keyboard. For Windows, replace cat with type (as far as I remember...)

user3640029
  • 165
  • 4