4
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Lucaci Andrew
0

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.

0

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

1

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);
    cin.ignore();
    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];
    answer[80]='\n';
    cout<<"> ";
    cin.get(answer, 79);
    cin.ignore();
    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.