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!