Enter the numbers on the keyboard into the array, but only 1 line

Is there a way to input numbers (separated by spaces) on one line in an array? I mean, I wrote like this:

First I introduced sizeofarray. Then I used the [for] loop to enter each number into each element. In this method, I had to press enter every time

So I want:

First enter sizeofarray. Then, in one line, enter all numbers for all elements, each of which is separated by a space

Example: 7, enter

1 5 35 26 5 69 8, enter

So, all numbers are stored in selected elements.

I know that my English is not very good, and I am not a very good coder. Therefore, please explain it easily. Thanks: D

+7
c ++ arrays
source share
4 answers

I don’t know why everyone is trying to do this in String style.
it's just that c ++ std :: cin can get it so easily

int main (){ int a[1000],sizeOfA; cin>>sizeOfA; for (int i=0;i<sizeOfA;i++) cin>>a[i]; 
+7
source share

If you are going to enter all the numbers on one line, then there is absolutely no need to start by entering the number of numbers that will follow.

You will need to read the entire line in the line, ( char[] ), and then parse that line to find substrings separated by spaces, and then you need to parse each substring into a number.

Exactly how to do this, we will not talk, because stackoverflow is not what others do your homework for you.

+2
source share

Reading at the input as a string, then splitting by spaces to get individual numbers:

 int main() { using namespace std; int* nums; int size; cout << "Enter size of array"; cin >> size; nums = new int[size]; string input; cout << "Enter numbers, separated by single space:\n"; getline(cin, input); istringstream iss(input); string s; int i = 0; while (getline(iss, s, ' ') && i < size) { int num = atoi(s.c_str()); nums[i] = num; printf("%d\n", num); ++i; } return 0; } 
+2
source share

The most optimal and safe way is to use containers, iterators, and streams. If "istream_iterator" retrieves from a stream value other than "int", it will be equal to "end", so reading from the stream occurs before the first non-int or to the end

 #include <string> #include <vector> #include <iostream> #include <sstream> int main() { using namespace std; size_t size = 0; cin >> size; cin.ignore(); string buffer; getline(cin, buffer); stringstream ss(buffer); istream_iterator<int> iter(ss); istream_iterator<int> end; vector<int> vec; vec.reserve(size); for (size_t i = 0; i < size && iter != end; ++i, ++iter) { vec.push_back(*iter); } } 
0
source share

All Articles