stringstream

hi guys i am so exausted wit this. I trying to get input from the user and split into words that separated by a space. any idea?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

string s = "1 2 3"; 
    istringstream iss(s);   
    int n;

    while (iss >> n) {
        cout << "* " << n << endl;
    } 
//the code above works fine but i want to get the string from user. the code below only prints the first word and trashes rest of the words in the sentence.
string s ;
cin>>s;
    istringstream iss(s);   
    string n;

    while (iss >> n) {
        cout << "* " << n << endl;
    } 
Haha, one more newbie. No, that's not bad. Keep in mind what you'll learn. I use this in almost 90% of my programs. This magical gift name's std::getline. It read any stream and split it with the delimiter you want. The name is "get line" because the default delimiter is breakline ('\n').
Ok, lets apply one example:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
int main()
{
    std::string input;
    std::cout << "Input anything with spaces. ";
    std::getline(std::cin, input); //What? Oh, std::cin is a input stream!
//In this case, everything since the "\n" will be caught.
   std::cout << std::endl << "You input " << input;
}

So, it gets everything since the delimiter (from one input) to the specified write stream. You can use files, stringstreams, everything!

In your case, you would use:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <sstream>
int main()
{
    std::string input;
    std::string words;
    std::cout << "Input something. I'll split into words.\n> ";
    std::getline(std::cin, input); //I want to remember you something:
    //cin, cout, clog, cerr, etc are objects
    std::stringstream text(input);
    std::cout << "\nYou input: \n";
    while(std::getline(text, words,' ')) //Delimiter space ' '
    //you have to use a sstream, because string cant cast to basic_istream
    {
        if(!words.empty()) //if input is not ' '
        {
            std::cout << words << "\n";
        }
    }
}

Hope this help you!
Oh, and just for my knowledge: are you brazillian?
Thanks a lot that worked out. and i am not brazillian
Topic archived. No new replies allowed.