Alex Rivera | Logout

C++ strings and pointers

Asked 2012-03-04T12:21:18.307
13

I'm learning C++ and currently I'm working with strings and pointers.

I'm following an exercise book and for one of the questions I've created the following:

#include <iostream>
#include <string>

using namespace std;

int main(void){
    string * firstName=nullptr;
    string * lastName=nullptr;
    string * displayName=nullptr;

    cout << "Enter your first name: " << endl;
    getline(cin,*firstName);

    cout << "Enter your last name: " << endl;
    getline(cin,*lastName);

    displayName=new string;
    *displayName= *lastName + ", " + *firstName;

    cout << "Here's the information in a single string: " << displayName;
    cin.get();
    return 0;
}

In a bid to use more of pointers I've tried to mix it together with strings and have made the solution more complex for this reason. When I run this I get a "Unhandled Exception: Access violation reading location xxxxxxxxx".

Can someone please suggest a solution to this by still using pointers and strings instead of char arrays (which I've already figured out how to do)?

Edit
Report

1 Answer

2

It would look like this:

int main()
{
    std::string* s = new std::string;
    std::getline(std::cin, *s);
    std::cout << *s;
    delete s;
}

But there is really no reason to do so, just define a normal string variable on the stack.

answered 2012-03-04T12:25:41.053

Your Answer