splitting a string into an array in C++ without using vector

前端 未结 5 1658
轮回少年
轮回少年 2020-11-28 10:53

I am trying to insert a string separated by spaces into an array of strings without using vector in C++. For example:

using namespace std;
int main(         


        
5条回答
  •  清酒与你
    2020-11-28 11:07

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    template 
    void splitString(string (&arr)[N], string str)
    {
        int n = 0;
        istringstream iss(str);
        for (auto it = istream_iterator(iss); it != istream_iterator() && n < N; ++it, ++n)
            arr[n] = *it;
    }
    
    int main()
    {
        string line = "test one two three.";
        string arr[4];
    
        splitString(arr, line);
    
        for (int i = 0; i < 4; i++)
           cout << arr[i] << endl;
    }
    

提交回复
热议问题