Beginners Questions

I just got into C++ and I wanted to ask some fairly simple questions.
1.
#include <iostream>
using namespace std;
int main()
{
int name;
cout << "What is your name?" << endl;
cin >> name;
cout << "Hello " << name;
system("pause");
return 0;
}

I want it to show me my name but it only shows a number, what am i doing wrong?
The problem is that you're declaring your "name" variable as an int (a number). You need to use something like a char array or a string e.g.

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

using namespace std;
int main()
{
string name;
cout << "What is your name?" << endl;
cin >> name;
cout << "Hello " << name;
system("pause");
return 0;
}



When you declared the "name" variable, you declared it as an integer, which will only hold a number. You should use a string, which will store text input:

string name;

You'll need to include the <string> header to use it.
An alternative to using a string is using a character array. In this case you do not need to include <string>.

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

using namespace std;
int main()
{
char[50] name;
cout << "What is your name?" << endl;
cin >> name;
cout << "Hello " << name;
cin.get();
return 0;
}


Also as a friendly reminder, try to avoid using system(). It is slow, makes the program OS dependant and leaves a backdoor for intruders.
Thanks that really helped!
Topic archived. No new replies allowed.