+ 1

How do I use cin to take in a sentence?

#include <iostream> #include <string> using namespace std; int main() { string sentence; cin >> sentence; cout << sentence; } ^ This code should let me input a string, but it breaks off at the first word. If I input "Hello World" and output the string, I get only "Hello". Why is it like that? How can I input the whole sentence?

3rd Mar 2017, 5:34 PM
Rain
Rain - avatar
7 odpowiedzi
+ 1
Have a look at this too, # include <iostream.h> # include <conio.h> main() { char name[20],city[20]; clrscr(); cout<<"PLEASE ENTER THE NAME:->"; cin.getline(name,20); cout<<"PLEASE ENTER THE CITY:->"; cin.getline(city,20); cout<<"NAME IS:->"<<name<<endl; cout<<"CITY IS:->"<<city<<endl; }
3rd Mar 2017, 6:08 PM
Aamna Shahab
0
use getline() instead of cin. (header file for getline function is stdio.h)
3rd Mar 2017, 5:39 PM
Aamna Shahab
0
Thank you so much!! I used #include <stdio.h> but it wouldn't perform the getline function. It gave no errors either. I also was using namespace std. It was pretty weird.
3rd Mar 2017, 5:49 PM
Rain
Rain - avatar
0
So, is it working without stdio?? or not working at all?
3rd Mar 2017, 5:59 PM
Aamna Shahab
0
#include <iostream> int main () { std::string name; std::cout << "Please, enter your full name: " << std::endl; std::getline (std::cin,name); std::cout << "Hello, " << name << "!\n"; return 0; } I copied the example from a site
3rd Mar 2017, 6:02 PM
Rain
Rain - avatar
0
#include <iostream> using namespace std; int main () { string name; cout << "Please, enter your full name: " << endl; getline (cin,name); cout << "Hello, " << name << "!\n"; return 0; } nvm, it works like this, thank you so much. I would upvote your responses, but each time i try, it says "no internet connection" even though im posting stuff
3rd Mar 2017, 6:05 PM
Rain
Rain - avatar
0
hahah yes, do upvote if you feel like 😊 Thank you!
3rd Mar 2017, 6:09 PM
Aamna Shahab