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
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);
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.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With