excuse me but can someone teach me how to get a string with space
example : this author
i need to get the codes on how to get that
thank you

Recommended Answers

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 …

Jump to Post

All 3 Replies

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

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.

commented: Quality post! +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.