Thread: char as int error

  1. #1
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428

    char as int error

    Hello I am trying to teach myself C++ at night and I have started by writing things that are enjoyable such as basic games. I have come to a problem that for user input in choices i usually use a menu such as

    Code:
    void town()
    {
        hp = level * 10;
        int move;
        cout<<"You are in town.  You have "<<gold<<" gold and "<<attack<<" attack power.\n";
        cout<<"Would you like to\n";
        cout<<"1. Buy Weapons\n";
        cout<<"2. Buy Spells\n";
        cout<<"3. Adventure\n";
        cin>>move;
        if (move == 1)
        {
           buyweapons();
        }
        else if (move == 2)
        {
           buyspells();
        }
        else 
        {
           adventure();
        }
    }
    I know I was lazy and didn't require the user to re-choose if they choose above 3 I just had the last option choose to adventure regardless.

    My question is why can I not find a way around the entire game glitching if the user inputs a char or string of characters. I have tried to devise a way around it but after the glitch happens it seems to only register the next line of code and continually display it. Is there maybe a nuetral variable type I can have cin? Then through an if statement convert to either a char or int?

    I am sorry if this question has already been answered, but I couldn't find it by searching.
    Last edited by Lesshardtofind; 07-10-2009 at 12:56 AM. Reason: miskey in code

  2. #2
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    Put cin>>move in an if statement

  3. #3
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    if you mean

    Code:
     
        if(cin>>move)
        {
        if (move == 1)
        {
           buyweapons();
        }
        else if (move == 2)
        {
           buyspells();
        }
        else 
        {
           adventure();
        }
    }
    I just tried that and it still glitches... sorry if I misunderstood

  4. #4
    Novice
    Join Date
    Jul 2009
    Posts
    568
    What Tux0r said is that you should test that the input from cin was successfully assigned to move variable.

    Like this:
    Code:
    while (!(std::cin >> move)) { // while and if unable to assigning input to move
        std::cout << "Invalid input.\nTry again: "; // prompt the user again
        std::cin.clear(); // clear the error flags set in cin object, because they _are_ set when input fails
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // clear out the buffer
    }
    If the input can be assigned to move the loop body will not execute, otherwise it will keep looping until we get valid input.

    Edit: Opps. Bug on line4 and I forgot to mention that you must include limits header for this to work, e.g. #include <limits>.
    Last edited by msh; 07-10-2009 at 01:23 AM.

  5. #5
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    Thank you very much great answer in just a few lines of code. What does STD stand for? I haven't run into this yet with the tutorials. I spend more time coding than reading I try to apply what a learn as I go. If this will be answered shortly just ignore the question. lol

  6. #6
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Quote Originally Posted by Lesshardtofind View Post
    What does STD stand for? I haven't run into this yet with the tutorials. I spend more time coding than reading I try to apply what a learn as I go. If this will be answered shortly just ignore the question. lol
    It has to do with namespaces. Look it up.

    You probably have using namespace std; in your code, I use the scope operator :: on per use basis. They both achieve the same result but the scope operator offers more granulated control.

  7. #7
    C++11 User Tux0r's Avatar
    Join Date
    Nov 2008
    Location
    Sweden
    Posts
    135
    Quote Originally Posted by Lesshardtofind View Post
    Thank you very much great answer in just a few lines of code. What does STD stand for? I haven't run into this yet with the tutorials. I spend more time coding than reading I try to apply what a learn as I go. If this will be answered shortly just ignore the question. lol
    std is for standard, use it.

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    You could also put it into a function, of course:

    Code:
    bool reprompt(const std::string& msg, std::istream& iss, std::ostream& oss = std::cout)
    {
    	if (iss)
    		return false;
    	iss.clear();
    	iss.ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
    	oss << msg;
    	return true;
    }
    
    int main(void)
    {
    	int value;
    	cout << "Please enter an integer value> ";	
    	while (reprompt("Invalid input, please reenter an integer value> ", cin >> value))
    		continue;
    	cout << "value: " << value << endl;
    	return 0;	
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  9. #9
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    I already had to make it into a function since the game already has 3000 lines of code and alot of user input menus. Rather than bool I used an int. I don't understand the more complex code yet. I want to learn win api but it is daunting at the moment so basic console programs is where I am at right now. Any suggestions on how to convert this to basic graphics without learning the win api and direct draw? I believe those are over my head at the moment.

    I just used an int function

    Code:
    int checkanswer(int movea)
    {
         while (!(std::cin >> movea)) 
         { // while and if unable to assigning input to move
               std::cout << "Don't be a queer\nTry again: "; // prompt the user again
               std::cin.clear(); /* clear the error flags set in cin object, because      
                     they_are_ set when input fails*/
               std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n'); /* clear
                    out the buffer*/
        }
        return movea;
    }
    then in the functions that had options just changed all

    Code:
    cinn>>choice;
    to
    Code:
    choice =checkanswer(choice);

  10. #10
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> Any suggestions on how to convert this to basic graphics without learning the win api and direct draw?

    You might look into SDL.

    >> I already had to make it into a function since the game already has 3000 lines of code and alot of user input menus.

    If you use a function such as the one I posted you'll actually reduce the amount of code you have to write in the long run since it's completely reusable. For instance, let's say you wanted to enter two pieces of data instead - simple:

    Code:
    int main(void)
    {
    	int value;
    	string text; 
    	cout << "Please enter an integer value and a text string> ";	
    	while (reprompt("Invalid input, please reenter an integer value and a text string> ", cin >> value >> text))
    		continue;
    	cout << "value: " << value << endl;
    	cout << "text: " << text << endl;
    	return 0;	
    }
    The function you posted on the other hand only works for ints and for a specific hard-coded variable.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  11. #11
    Bored Programmer
    Join Date
    Jul 2009
    Location
    Tomball, TX
    Posts
    428
    Thank you. I will keep that in mind.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  2. Using VC Toolkit 2003
    By Noobwaker in forum Windows Programming
    Replies: 8
    Last Post: 03-13-2006, 07:33 AM
  3. Connecting to a mysql server and querying problem
    By Diod in forum C++ Programming
    Replies: 8
    Last Post: 02-13-2006, 10:33 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. C++ compilation issues
    By Rupan in forum C++ Programming
    Replies: 1
    Last Post: 08-22-2005, 05:45 AM

Tags for this Thread