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?
using C++ istringstream class. Assign input string to istringstream object and within a loop extract each word . for example, if the string is “hello world” then hello and world will be extracted and it can be stored in a data structure or process it.
The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
You can get the length of a string object by using a size() function or a length() function. The size() and length() functions are just synonyms and they both do exactly same thing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With