How to read in user entered comma separated integers?

后端 未结 9 534
轮回少年
轮回少年 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

    All of the existing answers are excellent, but all are specific to your particular task. Ergo, I wrote a general touch of code that allows input of comma separated values in a standard way:

    template<class T, char sep=','>
    struct comma_sep { //type used for temporary input
        T t; //where data is temporarily read to
        operator const T&() const {return t;} //acts like an int in most cases
    };
    template<class T, char sep>
    std::istream& operator>>(std::istream& in, comma_sep<T,sep>& t) 
    {
        if (!(in >> t.t)) //if we failed to read the int
            return in; //return failure state
        if (in.peek()==sep) //if next character is a comma
            in.ignore(); //extract it from the stream and we're done
        else //if the next character is anything else
            in.clear(); //clear the EOF state, read was successful
        return in; //return 
    }
    

    Sample usage http://coliru.stacked-crooked.com/a/a345232cd5381bd2:

    typedef std::istream_iterator<comma_sep<int>> istrit; //iterators from the stream
    std::vector<int> vec{istrit(in), istrit()}; //construct the vector from two iterators
    

    Since you're a beginner, this code might be too much for you now, but I figured I'd post this for completeness.

    0 讨论(0)
  • 2020-12-07 02:54

    You can use getline() method as below:

    #include <vector>
    #include <string>
    #include <sstream>
    
    int main() 
    {
      std::string input_str;
      std::vector<int> 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.

    0 讨论(0)
  • 2020-12-07 02:55
    #include<bits/stdc++.h>
    using namespace std;
    int a[1000];
    int main(){
        string s;
        cin>>s;
        int i=0;
        istringstream d(s);
        string b;
        while(getline(d,b,',')){
            a[i]= stoi(b);
            i++;
        }
        for(int j=0;j<i;j++){
            cout<<a[j]<<" ";
        }
    }
    

    This code works nicely for C++ 11 onwards, its simple and i have used stringstreams and the getline and stoi functions

    0 讨论(0)
提交回复
热议问题