Read an array from standard input, ignoring brackets and commas

前端 未结 4 617
广开言路
广开言路 2021-01-16 12:05

The sample input to my code is:

{ 1, 2, 3, 4 }

I wish to ignore the curly brackets and commas, and read the numbers into an array.

4条回答
  •  被撕碎了的回忆
    2021-01-16 12:49

    Hmmm, this might work:

    // Ignore all characters up to and including the open curly bracket
    cin.ignore(100000, '{');
    
    // Read the numbers into an array
    int my_array[4];
    unsigned int array_index = 0;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    array_index++;
    cin >> my_array[array_index];
    
    // Ignore all characters up to and including the newline.
    cin.ignore(1000000, '\n');
    

    You could use a for loop to read in the numbers.

提交回复
热议问题