My very first program

I've written my very first program were I am prompting the user to enter all their first names and their last name(s)

When I run it it doesn't print out the full name but it does when i tell the program to print out first name and last name

Working:

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

using namespace std;

int main()
{
    string firstName;
    string lastName;
        cout << "Type your first names: ";
        getline (cin,  firstName);
        cout << "Type your last name: ";
        getline (cin,  lastName);
        cout << "Your name is: " << firstName << " " << lastName;
        
        
}


Not working:

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

using namespace std;

int main()
{
    string firstName;
    string lastName;
    string fullName = firstName + lastName;
        cout << "Type your first names: ";
        getline (cin,  firstName);
        cout << "Type your last name: ";
        getline (cin,  lastName);
        cout << "Your name is: " << fullName;
        
        
}


What am I doing wrong?
Last edited on
> string fullName = firstName + lastName;
Because C++ doesn't change the past.

Doing this before you do this makes no sense.
1
2
3
string fullName = firstName + lastName;
...
getline (cin,  firstName);


No, you don't get a new fullName everytime you make a change to firstName.
Your second attempt, line 9.....move it to after line 14.

Your "failure" is because you are concatenating two EMPTY strings together, before you get user input for the strings.

The same problem is in both programs, you just don't use fullName in your "working" example so don't notice the logic error.
Putting all that together plus a bit:

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

using namespace std;

int main()
{
    string firstName;
    string lastName;
    
    cout << "Type your first names: ";
    getline (cin,  firstName);
    
    cout << "Type your last name: ";
    getline (cin,  lastName);
    
    string fullName = firstName + ' ' + lastName;
    cout << "Your name is: " << fullName << '\n';
}


Type your first names: Arthur Mary
Type your last name: Scott_Fitzgerald
Your name is: Arthur Mary Scott_Fitzgerald
Program ended with exit code: 0
Thank you all for your input.
I was able to solve it and realize what I did wrong.

I have to keep writing from top to bottom as the programm will be read that way.

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

using namespace std;

int main()
{
    string firstName;
    string lastName;
            cout << "Type your first names: ";
        getline (cin,  firstName);
        cout << "Type your last name: ";
        getline (cin,  lastName);
    string fullName = firstName + " " + lastName;
        cout << "Your name is: " << fullName;
        
        
}
Topic archived. No new replies allowed.