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)?
In C, a string can be referred to either using a character pointer or as a character array.
Strings are used for storing text/characters. For example, "Hello World" is a string of characters. Unlike many other programming languages, C does not have a String type to easily create string variables.
String in C programming is a sequence of characters terminated with a null character '\0'. Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a unique character '\0'.
Accessing string via pointer To access and print the elements of the string we can use a loop and check for the \0 null character. In the following example we are using while loop to print the characters of the string variable str .
I think, you don't want to use pointers
at all. You can work with strings
without pointers.
#include <iostream>
#include <string>
using namespace std;
int main(void){
string firstName;
string lastName;
string displayName;
cout << "Enter your first name: " << endl;
getline(cin,firstName);
cout << "Enter your last name: " << endl;
getline(cin,lastName);
displayName= lastName + ", " + firstName;
cout << "Here's the information in a single string: " << displayName;
cin.get();
return 0;
}
Othewise, if you need pointers, you have to allocate memory for variables:
cout << "Enter your first name: " << endl;
firstName = new string();
getline(cin,*firstName);
...and print result with dereference operator (*
):
cout << "Here's the information in a single string: " << *displayName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With