How to input elements in an array WITHOUT inputting n? (c++)

Use a std::vector<long long> a; instead.

Then use long long temp;, cin >> temp;, and a.push_back(temp);.

This means that the vector will automatically grow as you add more data. There are in a sense smarter ways, but my way carries the advantage of clarity.

These days the cool cats don't worry about repeated push_back as they trust a C++ standard library implementation to keep the memory nice and unfragmented for you. But if you must, then std::vector does allow you to set an initial capacity via its reserve method: you can still grow your vector beyond that if you wish.


The standard input filter loop in C++ is while(cin >> a) - this will read until there is no more input, or other bad things happen:

#include <vector>
#include <iterator>
#include <iostream>
int main() {
  std::vector<int> nums;
  while (std::cin >> a) {
    nums.push_back(a);
  }
  std::copy(nums.begin(), nums.end(), ostream_iterator<int>{cout, " "});
}

You could also use a one liner with input iterators - the shortest way to read elements in a vector:

#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>

int main() {
  std::vector<int> nums(std::istream_iterator<int>(std::cin), {});
  std::copy(nums.begin(), nums.end(), std::ostream_iterator<int>{std::cout, " "});
}

See Ideone example here

Assuming however that you wish to ignore all this C++ awesomeness, strongly discouraged IMHO, you can just:

#include <iostream>
int main() {
  const int MAX_SIZE = 100;
  int nums[MAX_SIZE]; 
  int a;
  int i=0;
  while (std::cin >> a) {
    nums[i++] = a;
  }

  // do your output
}

Note that you will:

  1. need to guess the MAX_SIZE,
  2. or manually handle reallocation once you read more elements than MAX_SIZE;

Hence: use an std::vector!!

Tags:

C++