What is the easiest way to take string input from keyboard and then split this string based on how many words there are?
I've tried doing it the raw C++ way, but people said i can't and it's too hard. I should use STL instead. But how exactly? I can use vector <string> and take input from keyboard, if i'm not mistakig, but then how do you split it and store in a vector <string> again? This is a problem with general case, x long string and y words.
I need to do this, in order to have words stored and then calculate the frequency of how many times each word appears and display it like this.
getline() from std::cin into std::string
intialize std::istringstream object, stream, with the string
declare another std::string temp
read the stream into temp (it's parsed on white-space) and while it's being read-in send the temp string to a std::map<std::string, int> using the [] operator for map's which would increment count of words already present in the map
for consistency you may also wish to remove punctuations and upper/lower case the string temp first
Enoizat - unless OP shows some effort of their own try not to send out a full-fledged program, rather an outline to get them started (I must admit though that I have been guilty of this as well in the past)
Enoizat - unless OP shows some effort of their own try not to send out a full-fledged program, rather an outline to get them started
Hi, gunnerfunner.
Thank you for your directions. May I ask you if they are a personal position of yours or belong to the policy of this forum?
Thanks in advance for your answer.
To get the input from the keyboard use getline. To split the string use a stringstream and finally to count the frequency use a map<string, int>. Finally display all the words from the map.
Thank you, Thomas1965.
I read them when I subscribed this forum.
Is there any part which relates to what gunnerfunner said to me, in your opinion?
Thanks for your help.
getline( cin, line );
will take a single line containing multiple words from the keyboard. To extract individual words use a stringstream and put them in a map<string,int>. That is presumably what the OP wants and what all the code samples and advice above correctly leads to.
However, just suppose that you were reading from file - why do you need a stringstream in that case? Surely you can just extract the words directly one by one from file anyway?