How to read in user entered comma separated integers?

后端 未结 9 554
轮回少年
轮回少年 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 02:54

    You can use getline() method as below:

    #include 
    #include 
    #include 
    
    int main() 
    {
      std::string input_str;
      std::vector vect;
    
      std::getline( std::cin, input_str );
    
      std::stringstream ss(str);
    
      int i;
    
      while (ss >> i)
      {
        vect.push_back(i);
    
        if (ss.peek() == ',')
        ss.ignore();
      }
    }
    

    The code is taken and processed from this answer.

提交回复
热议问题