program stopped working

Im reading the book "Jumping in C++" and at the end of chapter 3 it gives you practice problems. The first is to write a program that outputs your name. The program I wrote I thought solved this however every time i put in my first name and hit the enter button it causes to program to stop working. The following is the error "A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available." I do not get any errors in the build log or any other sign why it doesnt work. Below is my code I have tried for this program. Thanks in advance for any help because the only thing I can find on searching for this is much more complicated programs and it typically had to do with the syntax used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>


using namespace std;

int main()
{
    int first_name;
    int last_name;
    cout << "Enter first name: ";
    cin >> first_name;
    cout << "Enter last name: ";
    cin >> last_name;
    cout << first_name + " " + last_name << endl;

}
The problem is that for the names, you are using an int. This means that the variable can only store a whole number.

Instead, use a string like this:
1
2
3
4
5
6
7
8
9
string first_name, last_name;

cout << "Enter your name first name: ";
cin >> first_name;

cout << "Enter your last name: ";
cin >> last_name;

cout << first_name + " " + last_name << endl;


or how I might do it:
1
2
3
4
5
6
string first_name, last_name;

cout << "Enter your name: ";
cin >> first_name >> last_name;

cout << first_name << " " << last_name << endl;


or even (with #include<string> ):
1
2
3
4
5
6
string name;

cout << "Enter your full name: ";
getline(cin, name);

cout << name << endl;
Awesome thanks, This is what i ended up doing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string first_name;
    string last_name;
    cout << "Enter first name: ";
    cin >> first_name;
    cout << "Enter last name: ";
    cin >> last_name;
    cout << first_name + " " + last_name << endl;

}
Last edited on
Topic archived. No new replies allowed.