CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Cin problem

  1. #1
    Join Date
    Mar 2011
    Posts
    4

    Cin problem

    basically i need the user to enter two numbers seperated by spaces. these numbers represent year and age respectively.

    eg 10 5

    if they enter just 10 i need to set year = -1 and age = -1
    if they enter characters instead of numbers i also need to store both numbers as -1

    the problem i have with my code is that when the user enters just one number and then hits enter, it waits forever for the user to enter another number. i dont know how to get around this using cin, given that it ignores whitespace. i know i could use getline and tokenise but that seems too complicated. any clues?

    i have the following code

    char year;
    char age;

    cout<<"What age to search for? =>";
    cin>>year;

    if(isdigit(year))
    {
    cin>>month;
    if(isdigit(month))
    {
    s.age[0] = static_cast<int>(year) - 48;
    s.age[1] = static_cast<int>(month) - 48;
    }
    else
    {
    s.age[0] = -1;
    s.age[1] = -1;
    }

    }
    else
    {
    s.age[0] = -1;
    s.age[1] = -1;
    }

    cin.ignore(100, '\n');

  2. #2
    Join Date
    Oct 2006
    Posts
    616

    Re: Cin problem

    Quote Originally Posted by eword View Post
    the problem i have with my code is that when the user enters just one number and then hits enter, it waits forever for the user to enter another number.
    Well, that's how cin works.

    Quote Originally Posted by eword View Post
    i know i could use getline and tokenise but that seems too complicated.
    Good idea! (except for the 'but that seems too complicated' part ).
    If you try doing as you suggested, maybe it won't seem so complicated.

    Regards,
    Zachm

  3. #3
    Join Date
    Aug 2009
    Posts
    440

    Re: Cin problem

    There are a few problems with what you have. First and foremost you are using chars. A char cannot hold 10. I would use strings. You will also need to look into getline. As it stands cin will wait for user input, if there is none, it will continue to wait.

  4. #4
    Join Date
    Mar 2011
    Posts
    4

    Re: Cin problem

    yeah your probably right. cheers. also thanks for pointing out the char variable. completely overlooked that.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured