c++ - taking input of a string word by word -
i started learning c++. playing around , came across problem involved taking input of string word word, each word separated whitespace. mean is, suppose have
name place animal
as input. want read first word, operations on it. read second word, operations on that, , read next word, on.
i tried storing entire string @ first getline
#include<iostream> using namespace std; int main() { string t; getline(cin,t); cout << t; //just confirm input read correctly }
but how perform operation on each word , move on next word?
also, while googling around c++ saw @ many places, instead of using "using namespace std" people prefer write "std::" everything. why's that? think same thing. why take trouble of writing again , again?
put line in stringstream , extract word word back:
#include <iostream> #include <sstream> using namespace std; int main() { string t; getline(cin,t); istringstream iss(t); string word; while(iss >> word) { /* stuff word */ } }
of course, can skip getline part , read word word cin
directly.
and here can read why using namespace std
considered bad practice.
Comments
Post a Comment