Problems with an easy C++ code

Hey guys,
I'm totally new to this forum and I'm also totally new to programming.
I've wrote this short code down below and it doesn't really work. Can anyone help me? :)
Oh, and I'm sorry if I spell something wrong! English is not my mother language ;)



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
#include<iostream>
using namespace std;


int main()
{
	int age;
         cout << "Please insert your age: " << endl;
	cin >> age;

	if (age < 18 )
		cout << "Acces denied! " << endl;
		getchar();


	if (age >= 18)
	{
		char name;
		cout << "Please insert your full name: " << endl;
		cin >> name;
		
		cout << "Good morning, " << name << endl;
		getchar();

	}

	return 0;
}



Edit:
I think the problem is in line 19 or 20. When I insert a name the program suddenly closes.

Last edited on
I've wrote this short code down below and it doesn't really work.


You'll need to describe more of the issue. What isn't working?

Also, put your code in code tags:
[code]Your code here[/code]
At the line:

 
char name;


You are declaraing a variable named 'name' which can contain a char, i.e. a single character. I think you intended a string which in the C world is an array of char's. If I were you I would use a std::string rather than a char array.
It still doesn't work...
Any other ideas?
Last edited on
#1 line 18: like said, use array of character atleast for name.(eg: char place[Constant])

#2 use cin.ignore() after cin.

#3 use cin.get() for array of characters followed by cin.ignore





It doesn't work.. I'm out of ideas :D
You need to be more specific about what isn't working. If the main problem is the console suddenly closes after the last input, just add cin.get() above return 0;.

If that is the problem, my suggestion really isn't a proper solution for it. Posting your updated codes would help in figuring out what's wrong.
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
#include<iostream>
using namespace std;

const char MAX_LENGTH = 32;

int main()
{
	int age;
	cout << "Please insert your age: " << endl;
	cin >> age; //leaves a newline in the input stream
	cin.ignore(); //so here we ignore the newline

	if (age < 18 )
	{
		cout << "Acces denied! " << endl; 
		cin.get(); //wait for input
	}
	else //no need for a new if statement here, only 2 possible outcomes, and it can never be both
	{
		char name[MAX_LENGTH]; //a non-initialized array of 32 char's
		cout << "Please insert your full name: " << endl;
		cin.getline(name, MAX_LENGTH); //gets the whole line of your input, does NOT leave a newline in the input stream. Assigns the data to name as a string (terminated by '\0')
		
		cout << "Good morning, " << name << endl;
		cin.get(); //wait for input
	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.