C++ split string

后端 未结 3 1329
感情败类
感情败类 2020-12-04 02:31

I am trying to split a string using spaces as a delimiter. I would like to store each token in an array or vector.

I have tried.

    string tempInput         


        
3条回答
  •  一个人的身影
    2020-12-04 02:43

    Notice that it’s much easier just to use copy:

    vector tokens;
    copy(istream_iterator(cin),
         istream_iterator(),
         back_inserter(tokens));
    

    As for why your code doesn’t work: you’re reusing tempInput. Don’t do that. Furthermore, you’re first reading a single word from cin, not the whole string. That’s why only a single word is put into the stringstream.

提交回复
热议问题