Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

c++ - taking input of a string word by word

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 whitespace. What I mean is, suppose I have

   name  place animal 

as the input. I want to read the first word, do some operations on it. Then read the second word, do some operations on that, and then read the next word, so on.

I tried storing the entire string at first with getline like this

    #include<iostream>
    using namespace std;
    int main()
    {
     string t;
     getline(cin,t);
     cout << t; //just to confirm the input is read correctly
    }

But then how do I perform operation on each word and move on to the next word?

Also, while googling around about C++ I saw at many places, instead of using "using namespace std" people prefer to write "std::" with everything. Why's that? I think they do the same thing. Then why take the trouble of writing it again and again?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

#include <iostream>
#include <sstream>
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...