用字符分隔数字

Separating numbers with characters

本文关键字:数字 分隔 字符      更新时间:2023-10-16

所以我想得到一个数字列表。所以 1,2,3-5 会说1,2,3,4,5这是我到目前为止编码的内容

cin>>num; 
vec.push_back(num);
if(cin.peek() == ',')
    cin.ignore();

我该如何做范围部分?

点击这里阅读更多关于cin.peek()

单击此处查看一个很棒的堆栈溢出问题

点击这里 我用这个来源来帮助你。

我假设您正在使用命名空间标准如果您需要更多澄清注释,我将在我的代码中添加更多注释。

 cin>>ws;       //eats up white spaces
 cout.flush(); 
    do          //loop to check every number
    {
        cin>>num1; 
        num_vec.push_back(num1);
        if(cin.peek() == ',')
        {
            cin.ignore();
        }
        else if(cin.peek() == '-')      
        {
            cin.ignore();
        //if it sees a dash it will ignore the dash
       // similar to what you did with your comma 
            cin>>num2;
            for(++num1; num1<=num2; num1++)
            {
                num_vec.push_back(num1);
      //keeps adding 1 to that range and pushing it back to vector 
            } 
                if(cin.peek() == ',')
                {
                    cin.ignore();
                }       
        }
    }while(cin.peek() != 'n');