Reputation: 3050
Does it matter if I use a string or char for a simple input function? (aka y/n)
This is what I'm using at the moment:
using namespace std;
string somestr;
getline(cin,somestr);
if(somestr.empty())
{ //do something }
else if (somestr == "y"){
//do something else
}
else{}
And if it makes more sense to user char what would be the equivalent char code to this?
Upvotes: 0
Views: 355
Reputation: 245
It is better to use char because you only need to store one character
using namespace std;
char chr;
getline(cin,chr);
if(chr == null) { //do something } else if (chr == "y"){ //do something else } else{}
Upvotes: 0
Reputation: 19603
I think James McNellis gives good rationale for why you would use either case. Personally, if you're asking a "yes/no" question, I find the single character easier because it minimizes the number of different scenarios you have to deal with.
Here's some sample code that you could use to read an answer from the user via a single character:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
//keep looping until the user enters something valid
while(true)
{
char answer;
cout << "Does this sound good (y/n)? ";
cin >> answer;
if(answer == 'y' || answer == 'Y')
{
//user entered yes, do some stuff and leave the loop
cout << "You answered yes!" << endl;
break;
}
else if(answer == 'n' || answer == 'N')
{
//user entered no, do some stuff and leave the loop
cout << "You answered no!" << endl;
break;
}
else
{
cout << "You did not enter a valid answer. Please try again." << endl;
//if we got bad input (not 'y'/'Y' or 'n'/'N'), wipe cin and try again
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
}
}
}
If you're planning on reading more than a single character answer though, then I think you're probably fine with getline
and doing your reasoning that way.
Upvotes: 2
Reputation: 354969
Yes, it matters, because std::string
cannot be compared with a char
using ==
. You can compare it with a string literal:
if (somestr == "y")
or you can test the initial element of the std::string
:
if (somestr[0] == 'y')
In the latter case, you might want to check the length as well, otherwise you would accept such inputs as "yacht" and "yellow." Comparing with a string literal containing the expected text is probably a better choice for most use cases.
Upvotes: 5