Michael Blake
Michael Blake

Reputation: 995

Using cin, how can I accept a character or an integer as an input?

I'm writing a program that accepts a card rank as an input, then coverts these ranks into the values they represent. So some examples would include A, 5, 10, K. I've been trying to figure out ways to do this.

I thought about accepting it as a char, then converting it, like so...

char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}

And that would work...except for 10 unfortunately. What's an option that works?

Upvotes: 2

Views: 2040

Answers (3)

kiran
kiran

Reputation: 37

We should use char array of size 2 because we can not store 10 in a char. Here is the sample program :

#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>

using namespace std;

int main()
{
  char s[2];
  cin >> s;

if( (s[0] < 58 && s[0] > 48) && ( s[1] == '\0' || s[1] == 48) )
{
  int m;
  m = atoi(s);
  cout << "integer  " << m << endl;

}
else if(s[0] < 123 && s[0] > 64)
{
  char c;
  c = s[0];
  cout << "char  " << c << endl;
}
else
{
  cout << "invalid input" << endl;
}
return 0;
}

Upvotes: 0

iksemyonov
iksemyonov

Reputation: 4196

Why not use std::regex when we're in 2016? @Michael Blake, is it a hard requirement to implement the parsing by hand?

I've been able to achieve the desired effect like so:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::regex regexp("[KQJA2-9]|(10)");
    std::string in;
    for (;;) {
        std::cin >> in;
        std::cout << (std::regex_match(in, regexp) ? "yes" : "no") << std::endl;
    }
}

Upvotes: 2

River
River

Reputation: 9093

Why not use the code you have, and just have a special case, in a third if block, to handle 10?

Since there's no valid input besides 10 that starts with a 1, this should be pretty straightforward:

char input = 0;
std::cin >> input;
if(input < 58 && input > 49) //accepting 2-9
{
//convert integers
}
else if(input < 123 && input > 64)
{
//convert characters and check if they're valid.
}
else if(input == 49){ //accepts 1
    std:cin >> input; //takes a second character
    if(input == 48){ //this is 10
        //do stuff for 10
    }
    else{
        //throw error, 1 followed by anything but 0 is invalid input
    }
 }

Upvotes: 2

Related Questions