Welcome, Guest. Please login or register.

Author Topic: C/C++ programming  (Read 4181 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline jonssonjTopic starter

  • Sr. Member
  • ****
  • Join Date: Oct 2003
  • Posts: 254
    • Show only replies by jonssonj
C/C++ programming
« on: November 08, 2005, 12:51:05 PM »
Hello!

I wonder how I can check that a input made by a user, really is an integer and not anything else.

F.eg.

#include

using namespace std;

int main(void)
{
   int test;
   cout << "Enter integer: ";
   cin >> test;

   // Now I want to check that the user really entered an
   // integer and not anything else.
}


BR
Jörgen Jönsson
 

Offline countzero

  • Hero Member
  • *****
  • Join Date: Mar 2005
  • Posts: 1938
    • Show only replies by countzero
    • http://blog.coze.org
Re: C/C++ programming
« Reply #1 on: November 08, 2005, 01:27:21 PM »
I'm not a C/C++ expert, but the simplest way to do it would be to take the input in a character string and parse each character if it's a value between 0-9. Then you can convert it into a integer variable.
I believe in mt. Fuji
 

Offline Amiga1200PPC

  • Newbie
  • *
  • Join Date: Sep 2002
  • Posts: 25
    • Show only replies by Amiga1200PPC
Re: C/C++ programming
« Reply #2 on: November 08, 2005, 02:00:50 PM »
Why do you want to check that anyways?
 

Offline Cymric

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 1031
    • Show only replies by Cymric
Re: C/C++ programming
« Reply #3 on: November 08, 2005, 02:31:11 PM »
The easiest way is by making use of sscanf(). Assuming you have the user input in an array of char buf with its starting tabs, spaces and letter symbols removed, you can simply call on

retval=sscanf(buf, "%d", &intval);

If retval equals 1, you have bagged an integer, the value of which is in intval. The downside is that it breaks down when faced with input which exceed the capacity of int, and ignores any remaining text in the input line after a non-number symbol was parsed. Also, sscanf() will not tell you what the user input was when it returns 0 indicating no match was made. In this case, your best bet is to simply put out a 0x07-character (\b if memory serves me) for the terminal beep, warn the user with a text, and redo the input.
Some people say that cats are sneaky, evil and cruel. True, and they have many other fine qualities as well.
 

Offline mgerics

  • Sr. Member
  • ****
  • Join Date: Jun 2002
  • Posts: 294
    • Show only replies by mgerics
Re: C/C++ programming
« Reply #4 on: November 08, 2005, 03:03:08 PM »
 

Offline melott

  • Hero Member
  • *****
  • Join Date: Dec 2002
  • Posts: 989
    • Show only replies by melott
Re: C/C++ programming
« Reply #5 on: November 08, 2005, 03:06:12 PM »
You may want to consider joining this group ...
       Amiga_BCG@yahoogroups.com

The guy running it is very good and responds
to all questions
Stealth ONE  8-)
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: C/C++ programming
« Reply #6 on: November 08, 2005, 04:34:50 PM »
If you want properly validated input you generally need to do it yourself. There are lots of examples of char by char input through stdio.
int p; // A
 

Offline uncharted

  • Hero Member
  • *****
  • Join Date: Mar 2002
  • Posts: 1520
    • Show only replies by uncharted
Re: C/C++ programming
« Reply #7 on: November 08, 2005, 04:45:37 PM »
Quote

Karlos wrote:
If you want properly validated input you generally need to do it yourself. There are lots of examples of char by char input through stdio.


That's why Java is so much better :-)

/me runs away from Karlos
 

Offline Karlos

  • Sockologist
  • Global Moderator
  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 16879
  • Country: gb
  • Thanked: 5 times
    • Show only replies by Karlos
Re: C/C++ programming
« Reply #8 on: November 08, 2005, 04:49:14 PM »
@uncharted

Or a library with validated input routines provided ;-)
int p; // A
 

Offline smithy

  • Hero Member
  • *****
  • Join Date: Mar 2002
  • Posts: 511
    • Show only replies by smithy
Re: C/C++ programming
« Reply #9 on: November 08, 2005, 04:58:39 PM »
Quote

jonssonj wrote:
Hello!

I wonder how I can check that a input made by a user, really is an integer and not anything else.

int main(void)
{
   int test;
   cout << "Enter integer: ";
   cin >> test;

   // Now I want to check that the user really entered an
   // integer and not anything else.


Add this:

Code: [Select]

   if(cin.fail())
   {
       // a number wasn't entered
   }
   else
   {
      if(!cin.eof())
      {
          // there is more non-numeric input
      }
   }
}


 

Offline jonssonjTopic starter

  • Sr. Member
  • ****
  • Join Date: Oct 2003
  • Posts: 254
    • Show only replies by jonssonj
Re: C/C++ programming
« Reply #10 on: November 09, 2005, 10:19:34 AM »
Hello all!

I use two functions that solves the problem I had.

One from MSDN that clears the cin buffer and one function that I wrote myself, that checks if the input is an integer or not.

Code: [Select]


int main(void)
{
char *buffer = 0;
buffer = new char[11];
int x=0;
int nState=0;

bool inmatning = true;

while(inmatning)
{
          // ................
          // other code goes here
          // ...................

          // I only saves 9 numbers so the biggest
          // number a user can enter is 999999999.
          cin.getline(buffer,10);
          nState = ClearError(cin);
          if(CheckForInteger(buffer))
 {
            x=atoi(buffer);
            if (x>=0)
   {
              //.................
              // other code goes here..
              //..................
            } else
               inmatning=false;
          } else
              cout << &quot;\nWrong input!&quot;;
        }
}


// Function from MSDN
int ClearError(istream& isIn)        // Clears istream object
{
    streambuf*  sbpThis;
    char        szTempBuf[20];
    int         nCount, nRet = isIn.rdstate();

    if  (nRet)                        // Any errors?
    {
        isIn.clear();                 // Clear error flags
        sbpThis = isIn.rdbuf();       // Get streambuf pointer
        nCount = sbpThis->in_avail(); // Number of characters in buffer

        while (nCount)                // Extract them to szTempBuf
        {
            if  (nCount > 20)
            {
                sbpThis->sgetn(szTempBuf, 20);
                nCount -= 20;
            }
            else
            {
                sbpThis->sgetn(szTempBuf, nCount);
                nCount = 0;
            }
        }
    }

    return  nRet;
}


// Function that checks if it's an integer or not.
bool CheckForInteger(char *input)
{
// int max = 2147483647;


// Initialize some variables.
bool heltal = true;
int length = 0;

// continue until the last char.
while(*input !='\0')
{
// if we find a '-' sign at the first pos.
// we ignore it.
if ( !(*input=='-' && length==0) )
{
// check if the current char is a
                        // digit.
if (!isdigit(*input))
{
// if not, we set the returnvalue to false.
heltal = false;
}
}
// go to next char and count allt the chars.
input++; length++;
}

// go back to first char in buffer.
input = input - length;

// return result.
return heltal;

}





Thanks for all your help and thanks for a great forum and a great community.

BR
Jörgen Jönsson

===========================================
Now I only owns one A500. I will buy a A-One when a new
model reaches the market (I'm optimistic :) )