cin / if statment issue ...

Hi all,

Im new to this forum, so first up, greetings!

Secondly, ive only recently got into C++ and need a bit of help.

I'm wondering how you can get your console program to recognise variable char's.

For example -
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>

int main()

{
	using namespace std;
	int age;
	char name [5];
	
		cout << "Hi, whats your name? \n" ;
	
	cin >> name ;

		cout << " So " << name  << " how old are you? \n";

	cin >> age;

		if (age > 20)

cout << " Great!\n";

else 

cout << " too bad your too young \n ";

		return 0;

}


You can see that the if statement recognises int variables and can decipher whether or not the input from cin is greater than 20.

Is there a way you can use an if statement to, for example decipher between the word yes or no. Or distinguish between 2 names?

It's being written in Microsoft Visual C++ 2008 if that helps

Thanks in advance!
#include <string> and use str::string instead of character arrays
eg:
1
2
3
4
5
cout << "Would you answer yes? ";
string answer;
cin >> answer;
if ( answer == "yes" )
   cout << "Great!";


BTW you should indent your code in a more readable way

If you really want to compare character arrays use one of these functions:
http://www.cplusplus.com/reference/clibrary/cstring/strncmp/
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
Last edited on
Brilliant!

Thanks very much for your help

Mike
Topic archived. No new replies allowed.