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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...