the char data type error

Apr 29, 2019 at 10:54am
Hello Everyone!! when I type (y or Y) or (n or N) it correspondingly outputs the according to code. Also outputs "please enter correctly.." when I type say bean, dasdjaw etc but when I type (yes or Yes) or (no or No) or anything starting with y/Y/n/N.
it should say "please enter correctly.." since I specified that in code but rather it shows "Correct" and "Incorrect" respectively.

Does it mean, char takes only first character of user input not the whole string. also how do I fix it???
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>
#include <cmath>
using namespace std;

int main()
{
	char ans;
	cout << "number of letters in hello are 5:- (ans in y/n) " << endl;
	cin >> ans;
	
	if (ans == 'y' || ans == 'Y')
	{
		cout << "correct..";
	}
	
	else if (ans == 'n' || ans == 'N')
	{
		cout << "incorrect..";
	}
	
	else
	{
		cout << "please enter correctly..";
	}
		
	system("pause");
	return 0;
}
Apr 29, 2019 at 11:06am
char ans;

ans is a single char. One char. If you try to store more than one character in it (for example, the word "yes", which contains THREE characters), things will go wrong.

You cannot store more than one character in a char. If you want to store more than one character, use a string.
Apr 29, 2019 at 2:54pm
Thank You, I got that...
Topic archived. No new replies allowed.