0

(answered)how can i make the input able to work with multiple of words instead of 1 ?

#include <iostream> #include<string> using namespace std; int main(){ string s; string s1; cin>>s; for(int i=s.size()-1;i>=0;--i){ s1+=s[i]; } cout<<s1; return 0; } //for example if input "hello" output ="olleh" but if the input is "hello world" out put is still " olleh ".

16th May 2022, 7:10 AM
learner
learner - avatar
8 Answers
+ 4
#include <iostream> #include<string> using namespace std; int main(){ string s; string s1; getline(cin,s); for(int i=s.size()-1;i>=0;--i){ s1+=s[i]; } cout<<s1; return 0; } It work now...
16th May 2022, 7:39 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 3
Getline function which is in string header... It allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input.
16th May 2022, 7:45 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 2
cin stops when it encounters a blank space. That is why you only get one word. getline accepts the blank spaces as part of the string and stops at the end of the line('\n'). or when you hit the enter key.
16th May 2022, 10:22 AM
Bob_Li
Bob_Li - avatar
+ 1
Mihir Lalwani thanks but whats getline ,i like to know what i use ,so if u dont mind explaining
16th May 2022, 7:43 AM
learner
learner - avatar
+ 1
Mihir Lalwani so it only works under #include<string> not in normal codes
16th May 2022, 7:54 AM
learner
learner - avatar
+ 1
Ya
16th May 2022, 8:01 AM
Mihir Lalwani
Mihir Lalwani - avatar
+ 1
Here is a link which explains the parameters and ways you can use getline, as well as some problems you might encounter when using it. https://www.google.com/amp/s/www.geeksforgeeks.org/getline-string-c/amp/
16th May 2022, 3:19 PM
Bob_Li
Bob_Li - avatar
0
Bob_Li why do i have to type getline(cin,s) instead of s only
16th May 2022, 2:54 PM
learner
learner - avatar