Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

Input : 5

long long n;
cin>>n;
long long a[n];
for(long long i=0;i<n;i++){
    cin>>a[i];
}

How do I input elements of the array without inputting n?

This is what I look for :

Input : 1,2,3,4,5

cout << a[0] 

output:

1

like image 773
Nson Avatar asked Nov 05 '16 10:11

Nson


People also ask

How do you take an input from an array without knowing its size?

You can use String to take input and then convert/use it using Integer. parseInt() . Using this you don't have to allocate an oversized array.

How can I get array elements without knowing the size in C?

int reqArraySize; printf("Enter the array size: "); scanf("%d", &reqArraySize); After this you may proceed with this interger input array size : for(i=0;i<reqArraySize;i++) scanf("%d",&arr[i]); Hope this helps you.

How will you take input to an array in C?

Input and Output Array Elements Here's how you can take input from the user and store it in an array element. // take input and store it in the 3rd element ​scanf("%d", &mark[2]); // take input and store it in the ith element scanf("%d", &mark[i-1]);


1 Answers

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!!

like image 72
paul-g Avatar answered Oct 19 '22 10:10

paul-g