I'd like to use cin and I used char for the int type (do you call it like that?) and it just shows one letter of what typed. How can I get the whole sentence?
2 Answers
Since you're using c++ why not use std::string instead? Something like this should do what you're looking for:
#include <iostream> #include <string> int main() { using namespace std; string sentence; cout << "Enter a sentence -> "; getline(cin, sentence); cout << "You entered: " << sentence << endl; } 1 Comment
Loki Astari
My sentence are usually long and span more than one line, I may even break them up into multiple parts with punctuation so they will definitely be longer than a single line; In fact I don't remember, because it was probably in play school, the last time I wrote a real sentence that was short enough to fit on a single line.
use cin.getline()
char name[256]; cout << "What is your name?\n>"; cin.getline(name, 256); cout << "Your name is " << name; 2 Comments
templatetypedef
This is correct, but in C++ it's probably a better idea to be using
std::string and the free function std::getline instead of raw character arrays, as they're significantly safer and less error-proneNick Radford
@templatetypedef TBH, I've not used C++ since I had to in school, and even then I think I always used std::string. Just trying to help, haha.
char*and notcharstd::string. Tellingcinto get astd::stringmakes it read a line (sort of likefgetsin C), if I'm not mistaken.getlinemust be used to get an entire line.