1

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?

7
  • not a CPP for a long time, but I believe you want char* and not char Commented Jun 24, 2011 at 1:57
  • 1
    Better yet, std::string. Telling cin to get a std::string makes it read a line (sort of like fgets in C), if I'm not mistaken. Commented Jun 24, 2011 at 1:58
  • 3
    @Joey : Not a line, only a word. getline must be used to get an entire line. Commented Jun 24, 2011 at 2:09
  • 1
    It would be much easier to understand what you're saying if you showed the actual code. Commented Jun 24, 2011 at 2:20
  • hm not really cuz im just trying and wanted to know how cin works... Commented Jun 25, 2011 at 3:52

2 Answers 2

5

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; } 
Sign up to request clarification or add additional context in comments.

1 Comment

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.
2

use cin.getline()

char name[256]; cout << "What is your name?\n>"; cin.getline(name, 256); cout << "Your name is " << name; 

2 Comments

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-prone
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.