cin with std::string crashing

Hello all,

I'm sort of mystified (and embarrassed) by this. I'm trying to simply cin a std::string, and when I do, regardless of whether I use cin >> myString or getline(cin, myString), boom!, my program crashes. Now, the funny thing is that the first time this doesn't give me grief. The second cin statement is what causes the trouble. I've declared the string, so I'm not sure what might be causing this. It surely is user error, because when I migrated from VC++ to DevC++, this still happened. Can someone point me in the right direction here? Code below. Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

#include<iostream>
#include<string>

using namespace std;

class Person{
public:
	Person::Person(){
		string resp;		
		while(true){
			cout << "Please enter the ssn:" << endl;
			getline(cin, resp); //this one is fine
		    if(resp.length() != 2){
				cout << resp;
				cout << "Sorry, the length of this ssn is incorrect." << endl;
				continue;
			}
			_ssn = atoi(resp.c_str());
			cout << "Please enter the name:" << endl;
			getline(cin, resp); //boom!
			strcpy(_name, resp.c_str());
			cout << "Please enter the age:" << endl;
			cin.ignore();
			cin >> resp;
			_age = atoi(resp.c_str());
		}
	
	}
	Person::Person(int ssn, char *name, int age){
		_ssn = ssn;
		strcpy(_name, name);
		_age = age;
	}
	Person& operator=(const Person& p2){
		_ssn = p2._ssn;
		strcpy(_name, p2._name);
		_age = p2._age;
		return *this;
	}
	void Person::display(){
		cout << _ssn << ", " << _name << "," << _age << endl;
	}
	int Person::getSSN(){
		return _ssn;
	}
protected:
	int _ssn, _age;
	char *_name;
};
closed account (DSLq5Di1)
You haven't allocated any memory for char* _name. Why not store the name internally as a string?
+1 at sloppy.

char*s are not strings. If you want a string, use a string.
Ah-ha, indeed! Yeesh *embarrassed*. I'm aware of the differences; I was just poking around trying different things, and this is the reason for the mix-max. Thank you!
Topic archived. No new replies allowed.