How to read in user entered comma separated integers?

后端 未结 9 556
轮回少年
轮回少年 2020-12-07 02:14

I\'m writing a program that prompts the user for:

  1. Size of array
  2. Values to be put into the array

First part is fine, I create a dynamica

9条回答
  •  猫巷女王i
    2020-12-07 02:40

    A priori, you should want to check that the comma is there, and declare an error if it's not. For this reason, I'd handle the first number separately:

    std::vector dest;
    int value;
    std::cin >> value;
    if ( std::cin ) {
        dest.push_back( value );
        char separator;
        while ( std::cin >> separator >> value && separator == ',' ) {
            dest.push_back( value );
        }
    }
    if ( !std::cin.eof() ) {
        std::cerr << "format error in input" << std::endl;
    }
    

    Note that you don't have to ask for the size first. The array (std::vector) will automatically extend itself as much as needed, provided the memory is available.

    Finally: in a real life example, you'd probably want to read line by line, in order to output a line number in case of a format error, and to recover from such an error and continue. This is a bit more complicated, especially if you want to be able to accept the separator before or after the newline character.

提交回复
热议问题