Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input numbers by keyboard into array but only 1 line

Tags:

c++

arrays

Is there any way to enter numbers (seperated by spaces) on a single line into an array ? I mean, I used to write like this:

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

So what I want is:

First, enter sizeofarray. Then, on a single line, enter all numbers for all elements, each of it seperated by a space

Ex: 7, enter

1 5 35 26 5 69 8, enter

So that all numbers are stored into elements dedicated.

I know my English is not good and I'm not a good coder. So please explain it easy. Thanks :D

like image 750
clupper_stine Avatar asked Sep 03 '16 09:09

clupper_stine


People also ask

How do I input an array in one line?

It can be done the string way i.e. declare the string of maximum size and take input of the string, find its length and you can then know the number of elements in the input. Ex: taking 1000 as the maximum size of input, char arr[1000]; gets(arr); int len=strlen(arr);

How do I read an input array when the size is not known?

You can use pointer to float, do malloc for some predefined size, if your limit has reached while taking an input then do a realloc to increase the memory. You need to take care of previously accepted data while doing a reaccloc. Save this answer.


2 Answers

I don't know why everyone is trying to do it in String way..
it's simple that C++ std::cin can get it so easy

int main (){  
int a[1000],sizeOfA;
cin>>sizeOfA;
for (int i=0;i<sizeOfA;i++)
    cin>>a[i];
like image 132
Nour Alhadi Mahmoud Avatar answered Nov 03 '22 03:11

Nour Alhadi Mahmoud


If you are going to enter all numbers in a single line, then it is completely unnecessary to begin by entering the number of numbers that will follow.

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

Precisely how to do this, we won't tell, because stackoverflow is not about having others do your homework for you.

like image 21
Mike Nakis Avatar answered Nov 03 '22 02:11

Mike Nakis