How to store letters in a variable?

Aug 31, 2011 at 7:30am
Hello. I was trying to use struct as a way to store more information a person in a variable, and then print out the information. However, if I want to request a name (that is letters instead of numbers), how do I store them in a variable? If that is even possible. My code is as following atm:

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


#include "stdafx.h"
#include <iostream>

struct PersonalInfo
{
	int Name;
	int Age;
	int Job;
	int Gender;
};

void PrintInformation(PersonalInfo YourInfo)
{
	using namespace std;
	cout << "Hello " << YourInfo.Name << ", you're a " << YourInfo.Age << " " <<YourInfo.Gender << " who works as a " << YourInfo.Job << "." << endl;
}

int main()
{
	using namespace std;
	cout << "Hello. Please enter your personal information: " << endl;
	
	PersonalInfo YourInfo;
	cout << "What is your name: " << endl;
	cin >> YourInfo.Name;

	cout << "What is your age: " << endl;
	cin >> YourInfo.Age;

	cout << "What is your job: " << endl;
	cin >> YourInfo.Job;

	cout << "What is your gender: " << endl;	
	cin >> YourInfo.Gender;


	PrintInformation(YourInfo);


	
	cin.clear();
	cin.ignore(255, '\n');
	cin.get();


	return 0;
}
Aug 31, 2011 at 8:46am
If you want to store letters in a variable, don't make that variable an int.

I suggest you make it a std::string, from the <string> header.

string Name;
Aug 31, 2011 at 2:20pm
Moschops is correct. You can't store a letter in an int.

You can use string or an alternative is to use the char type. You don't need to include any additional headers for this. You would need to make an array of characters that can be filled with the cin.

1
2
3
4
5
6
7
struct PersonalInfo
{
	char Name[50];
	int Age;
	char Job [50];
	char Gender[6];
};
Aug 31, 2011 at 3:46pm
save yourself some headaches and use strings (not char arrays), until you understand the dangers involved with char arrays and know how to avoid them.
Last edited on Aug 31, 2011 at 3:47pm
Aug 31, 2011 at 3:59pm
Stewcond wrote:
You can't store a letter in an int.

Then explain this:
1
2
3
4
union LettersInAnInt {
   int number;
   char[4] letters;
};
It's all numbers in the end...
Sep 1, 2011 at 7:10pm
@Mathead200:

Yes's its all binary. "a" = 0110 0001 = 141.
Topic archived. No new replies allowed.