-1

Can you, please, help to get input of this format:

{1,2,3,4}

and convert it to array with integers?

    int * ns = new int [n];
    cin >> ns;

This does not work. How should I change it?

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
Bek
  • 45
  • 8

3 Answers3

0
using namespace std;
typedef istream_iterator<int> It;
vector<int> v;
copy(It(cin), It(), back_inserter(v));
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • You can read the documentation of the functions I used. It just copies all the s that it can from std::cin to the vector. – John Zwinck Feb 13 '13 at 12:56
  • Sure, the OP wasn't very clear about the input requirements...he/she should look at http://stackoverflow.com/a/1895584/4323 for a more elaborate explanation of how to make it support commas. Or write it a different way completely! – John Zwinck Feb 13 '13 at 12:59
  • I have tried the code. It read elements until a non-digit, non-\n character is entered from stdin. For example, if I type `12\n34\n56\n,` , v would contains {12, 34, 56} EDIT: `CTRL+D` can also be used to terminate the input. – Konfle Dolex Feb 13 '13 at 12:59
0

You need to read the elements one by one and store them into the array.

int aNoOfElements = 0;
cin >> aNoOfElements;
int *anArray = new int[ aNoOfElements];     //allocate memory to hold aNoOfElements

for( int i = 0; i < aNoOfElements; i++ )
{
     cin >> anArray[ i ];                   // Read each input
}
gamer_rags
  • 134
  • 12
0

You need to parse the input. Take the input as string, then check for the format conforming to what you want. An algorithm that you can use:

  1. Check whether the first character is '{'
  2. If yes, then initialize a variable (say temp) to hold the number that you're about to get (as a string) with empty string, else error
  3. read next character
  4. if it's between '0' and '9' then append it to temp and go back to step 3, else go to step 5
  5. if it's a comma or '}', then convert temp to integer and put it into the array, re-initializing temp with empty string, else error
  6. still on the same character, if it's a comma then go back to step 3, otherwise done

I hope you can turn above algorithm into working code, good luck :)

P.S.: Feel free to tell me if you spot a bug

LeleDumbo
  • 9,192
  • 4
  • 24
  • 38