6 Years
Discussion Span
Last Post by Lucaci Andrew

That's what tutorials, books, and teachers are for. We are not a teaching site.

Yes, I know it's simple, but you try to do it, and we can help you fix it.


Strings can hold spaces as long as you use getline(). If you're going for a string for each word, you could try using arrays or two cin >> example;'s.
Beginner Tutorial

Edited by Albino


You must use the getline method. Here's an easy example:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string answer;
    cout<<"> ";
    getline(cin, answer);
    cout<<"I have just inserted: "<<answer<<endl;
    return (0);

The getline(cin, answer); will take whatever you insert, even the spaces, till the ENTER signal is received (when dealing with chars if you overpass the initial state value, it will take only as much as it can: char a[4]; cin.get(a, 6); ; insert: abcdefg; output: abcde, a[4]='e';
If you do need to heavily use the getline(cin, answer); you'll probably stumble upon some buffer errors, that's because on further uses it will have some \n or \0 characters at the end of the string. That's why it's better to put the cin.ignore() line there.
You can do it without strings as well:

int main(){
    char answer[80];
    cout<<"> ";
    cin.get(answer, 79);
    cout<<"I have just inserted: "<<answer<<endl;
    return (0);

Here's a usefull web-site: getline c++
If you have further questions, just let us know.

Edited by Lucaci Andrew

Votes + Comments
Quality post!
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.