You are not logged in.

#1 2007-03-05 01:50:52

alpha_gamma
Member
Registered: 2007-03-05
Posts: 9

nCurses getch() question

Hello,

I have begun using nCurses and am using getstr(name) to enter charaters and it is working well. However I would like to enter multi-digit numbers and tried this:

double one;
one=getch();

This only enables me to enter one character. I want to enter '22' but it only lets me enter '2'. All of the books and online resources say getch() will only grab one character.I have searched all the resources but they don't have the example I'm looking for to handle multi-digit input for one data variable. So as my last resort I am submitting my question here.

Can someone help me out and explain a way that I can enter multi-digit variables with getch() or some other nCurses function?

Thanks again,

Andrew

Offline

#2 2007-03-05 04:28:32

phrakture
Arch Overlord
From: behind you
Registered: 2003-10-29
Posts: 7,879
Website

Re: nCurses getch() question

You need to loop.  Also, getch does not return a double.  It returns a character.  It's probably not even the right value.
Here's a quick example that may not work.

double get_number()
{
   char c;
   double result = 0;
   while((c = getch()) != KEY_ENTER) {
      if(c < '0' || c > '9') {
         fprintf(stderr, "you failed, %c is not a number\n", c);
         return -1;
      }
      result = result*10 +(c - '0');
   }
   return result;
}

Offline

#3 2007-03-07 00:03:16

alpha_gamma
Member
Registered: 2007-03-05
Posts: 9

Re: nCurses getch() question

Hello phrakture,

I tried your function out and it does take in multidigits numbers but I am receiving a -1 for any digit entered when I do a printw().

I think I'll have to work on conversion methods.  I'm going to see if I can read in a string then convert it into a double with strtol/strtod.  Also I might try getstr() and convert the value with atoi() to an integer or maybe use scanf() to get an integer.  I'll have to look at istringstream for conversion, it should be in the sstream header.

thanks again,

Andrew

Offline

#4 2007-03-07 00:15:16

phrakture
Arch Overlord
From: behind you
Registered: 2003-10-29
Posts: 7,879
Website

Re: nCurses getch() question

alpha_gamma wrote:

I'll have to look at istringstream for conversion, it should be in the sstream header.

Well, that's C++.  If you're using C++ that's a whole different ball game.  Converting in C++ is easy:

template <typename T> int to_int(const T& t)
{
   int ret = 0;
   std::stringstream ss;
   ss << t;
   if(ss >> ret)
      return ret;
   else
      throw std::range_error("invalid number entered: " + ss.str());
}

Offline

Board footer

Powered by FluxBB