-1

I am having trouble using cin to enter multiple single digits that are separated by a comma. So far i have tried using this

int size = 8;
// = {2,5,6,7,8,3,1,4} the values I wish to input
int nums[8];
cin >> nums [0] >> nums [1] >> nums [2] >> nums [3] >> nums [4] >> nums [5] >> nums [6] >> nums [7];
for (int i=0; i < 8; i++) {
    cout << nums[i] << " ";
}

When I input 2,5,6,7,8,3,1,4, only 2 0 0 0 0 0 0 0 is outputted. Is there any way to fix this by using cin?

  • You can read `csv` files using `fstream` and passing the delimiter as `,` You can also use `strtok` API to parse values. – AdamMenz Mar 12 '19 at 19:18

1 Answers1

0

You can use getline to read entire string and then iterate through it. String text;

getline(cin, text);

Or

while(!cin.eof()){ cin>>x>>y; arr[i]=x; i++; } 
Zoe
  • 27,060
  • 21
  • 118
  • 148
Neeraj Bansal
  • 380
  • 7
  • 23
  • It is so bad. You are using `cin` twice! Also `wile(!cin.eof())` is considered very bad. Instead use it directly: `while(cin >> x >> y)`. – AdamMenz Mar 12 '19 at 20:46
  • How will you detect the end of stream ? cin.eof is to detect end of stream and exit from the loop. Otherwise, your loop will never end. – Neeraj Bansal Mar 13 '19 at 07:16