taking input of a string word by word

后端 未结 3 1250
小鲜肉
小鲜肉 2020-12-02 13:53

I just started learning C++. I was just playing around with it and came across a problem which involved taking input of a string word by word, each word separated by a white

3条回答
  •  执念已碎
    2020-12-02 14:29

    Put the line in a stringstream and extract word by word back:

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        string t;
        getline(cin,t);
    
        istringstream iss(t);
        string word;
        while(iss >> word) {
            /* do stuff with word */
        }
    }
    

    Of course, you can just skip the getline part and read word by word from cin directly.

    And here you can read why is using namespace std considered bad practice.

提交回复
热议问题