GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 16-Nov-2004, 10:07
leitz leitz is offline
New Member
 
Join Date: Nov 2004
Posts: 20
leitz is on a distinguished road

Problem with int mixed with char,...


I have a problem with a code... If I type number lčike 1,2,3,10,33,1034... it is OK, but if I type like "10.4" or "44,7" or "test" it gets to "Number is not in range!", but then it doesnt ask me for writing "stava" again...what can I do?
CPP / C++ / C Code:
int stava=0;
...
   while(dep!=1)  
    {
      gotoxy(2,4);
      cprintf("Write number: );
      cin>>stava;
      if (stava<1 || stava>denar)
       {
        dep=0;
        clrscr();
        gotoxy(2,4);
        textcolor(14);
        cprintf("* Number is not in range! ");
        ;
        dep=0;
       }
      else if (stava>=1 || stava<=denar) { dep=1; }
     }
...

  #2  
Old 17-Nov-2004, 01:31
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,242
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
Quote:
Originally Posted by leitz
I have a problem with a code... If I type number lčike 1,2,3,10,33,1034... it is OK, but if I type like "10.4" or "44,7" or "test" it gets to "Number is not in range!", but then it doesnt ask me for writing "stava" again...what can I do?
Stop entering junK?

Actually, when you use cin to read an integer value and you type nondigits, cin will stop reading at the first nondigit and leave that character in the input stream. Next time you do a cin, it sees that same nondigit and returns 0, leaving that character again... and again... and again...

The second easiest way to prevent this is to read the entire input as a character array or a string then use scanf(), atoi() or string streams to convert the value.

The easiest way is to stop entering junK!
__________________

Age is unimportant -- except in cheese
  #3  
Old 17-Nov-2004, 04:45
leitz leitz is offline
New Member
 
Join Date: Nov 2004
Posts: 20
leitz is on a distinguished road
I must do something to prevent error in program, so if anyone else press any other char it tells him not to
I also tryed with
CPP / C++ / C Code:
int stava=0;
...
      if (stava<1 || stava>denar)
       {
        dep=0;
        clrscr();
        gotoxy(2,4);
        textcolor(14);
        cprintf("* Number is not in range! ");
        stava=0;;
        dep=0;
       }
...
Even if I set stava=0; it still goes and not reading new number... This is unlogical to me... There must be a way to reset it or something? I tryed with scanf() and atoi() , but I have some problems, I get error thet he can not converst to int from char...
  #4  
Old 17-Nov-2004, 08:43
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,693
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by leitz
I must do something to prevent error in program, so if anyone else press any other char it tells him not to
I also tryed with
CPP / C++ / C Code:
int stava=0;
...
      if (stava<1 || stava>denar)
       {
        dep=0;
        clrscr();
        gotoxy(2,4);
        textcolor(14);
        cprintf("* Number is not in range! ");
        stava=0;;
        dep=0;
       }
...
Even if I set stava=0; it still goes and not reading new number... This is unlogical to me... There must be a way to reset it or something? I tryed with scanf() and atoi() , but I have some problems, I get error thet he can not converst to int from char...

You set stava = 0 inside the loop, so while(stava<1 ...) causes the loop to repeat forever.

Now to your real problem: using cin>> to input a numeric value.

If you use cin>> to input a numeric quantity and the user enters something non-numeric, then cin is put into an error state. This is important: NOTHING else can be done with cin until the error condition is cleared. After you clear the error condition, then cin.ignore() can be used to empty the input buffer so that you can try cin>> again.

This error condition is easy to test and recover from, as I show in the following illustration. I still don't recommend cin>> for user input. (Use getline() to get the entire line, then perform analysis and conversion as you need.)

Try this (it requires the user to enter a value greater than zero and less than or equal to 20).

CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{

  int dep;
  int stava;
  int denar = 20;

  dep = 0;
  while(dep != 1) {
    cout << "Enter a number, between 0 and " << denar + 1 << ": "; 
    cin  >>  stava;
    if (!cin) { // cin error state must be cleared
      cin.clear();
      cin.ignore(BUFSIZ, '\n'); // ignores everything up to and including the '\\n'
      cout << "**** Illegal input: must be an integer" << endl;
    }
    else if ((stava < 1) || (stava > denar)) {
      cout << "* Number is not in range! " << endl;
    }
    else { // here we know that stavia >= 1 and stavia <= denar, don't we?
      dep = 1; // this gets you out of the loop
    }
  }
  cout << "You entered " << stava << endl;
  return 0;
}

Now, this still has a problem: if the user just presses "Enter" (without having entered any characters) the program just echos the newline and waits for some user input. This cannot be avoided when you use cin>> to enter a numeric value.

If you want to avoid this, then use getline() or some other method to read the entire line into a character array or a C++ string variable. Then use some function like atoi() or sscanf(), or something to extract the numeric value.

One final note: the program as I have shown here does not give any warning or error if the user enters, say 12.34 (it just uses the 12), or 6abc (it just uses the 6). If you want to detect and flag these as errors, you have to do a little more work.

Regards,

Dave
  #5  
Old 17-Nov-2004, 09:13
Dr. Evil Dr. Evil is offline
Member
 
Join Date: Oct 2004
Location: Netherlands
Posts: 120
Dr. Evil will become famous soon enough
You can also use a getch() loop that exits when the user presses enter. It would then get each character and print it to the output only if it is a number, or a backspace if the user pressed back.
  #6  
Old 17-Nov-2004, 09:40
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,693
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by Dr. Evil
You can also use a getch() loop that exits when the user presses enter. It would then get each character and print it to the output only if it is a number, or a backspace if the user pressed back.

There are certainly lots of ways to obtain a numeric value from user input.

The reason that I don't recommend getch() is that it is not part of the standard C or C++ i/o libraries.

Traditionally, Windows platform compilers from Borland and Microsoft have typically had convenient functions like getch() in <conio.h>, but there is no <conio.h> for GNU g++ or gcc.

Anyone out there using .NET? -- I know you're there; I can hear you breathing.--- Is there a getch() for .NET compilers?


If you want to use getch() for user input, you still have to convert the individual input characters to numerical values and add them into some numerical variable.

Since there are ways to solve this problem using standard library functions, I would rather still stick to something that will work everywhere.

Of course you could use the standard function getchar() to collect characters in an array and convert the resulting string to a numeric value (after checking for errors). Or you could use cin.getline(), as I suggested. In either case, you can use strtof(), strtol(), or sscanf(), or some other standard library conversion function to get the numerical value.

I was sticking with cin>>, since that's what the original poster was using. (I still don't recommend this, but something can be learned from the attempt.)

Regards,

Dave
  #7  
Old 17-Nov-2004, 14:18
leitz leitz is offline
New Member
 
Join Date: Nov 2004
Posts: 20
leitz is on a distinguished road
Thx davekw7x this works nice, but there is still some problem...
Let`s say I type "40.7484" or "40kjdh" ... ok, it takes 40 this is ok, but then when it goes back to "while" at the end of the game it writes "Number is not in range!" and then asks for typing again... Dont know why ge goes there first...

+another strange thing happens if I type lets say "4,22"... then it just taked "4" 2 times...
  #8  
Old 17-Nov-2004, 14:47
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,693
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by leitz
Thx davekw7x this works nice, but there is still some problem...
Let`s say I type "40.7484" or "40kjdh" ... ok, it takes 40 this is ok, but then when it goes back to "while" at the end of the game it writes "Number is not in range!" and then asks for typing again... Dont know why ge goes there first...

+another strange thing happens if I type lets say "4,22"... then it just taked "4" 2 times...

When you cin>> to an int, the scan of the input buffer stops when a non-numeric character is encountered. (White space: space, tab, newline are also non-numeric characters.) The remaining part of the user input for that line is still in the input buffer waiting for the next cin, getchar(), or whatever. You can use cin.ignore(SomeLargeNumber) to "eat" the rest of the input line so that next time the program executes "cin>>" it will wait for a new line from the user.

One more time: That's why experienced programmers tend not to use cin>> for user input. Lots of little details to clean up. cin.getline() reads the entire input buffer (including the new line) so next access is always a clean start.

People can use cin>> if they want to, but they must pay attention to details.

Regards,

Dave
  #9  
Old 17-Nov-2004, 15:06
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,693
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Here's a program that throws away all non-numeric characters and goes back for more. My previous code just quit when it got a good number, so if you entered, say 4.12, it wouldn't work inside a bigger loop. Here's an example of how to do it. Note that I changed the loop exit conditions slightly.

If this meets your needs, OK. But I still dis-recommend cin>> for user input.


CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main()
{

  int dep;
  int stava;
  int denar = 20;

  dep   = 1;
  stava = 1;
  while (stava) {
    while(dep) {
      cout << endl << endl << "Enter 0 to quit." << endl << endl;
      cout << "Enter a number, between 0 and " << denar + 1 << ": "; 
      cin  >>  stava;
      if (!cin) { // cin error state must be cleared
        cin.clear();
        cin.ignore(BUFSIZ, '\n');
        cout << "   **** Illegal input: must be an integer" << endl;
      }
      else if ((stava == 0)) {
          break;
      }
      else if ((stava < 1) || (stava > denar)) {
        cout << "   * Number is not in range! " << endl;
      }
      else { // here we know that stavia >= 1 and stavia <= denar, don't we?
        dep = 0; // this gets you out of the while(dep) loop
      }
    }

    cout << "   You entered " << stava << endl;
    cin.ignore(BUFSIZ, '\n');
    dep = 1;
  }
  return 0;
}

Regards,

Dave
  #10  
Old 17-Nov-2004, 15:10
leitz leitz is offline
New Member
 
Join Date: Nov 2004
Posts: 20
leitz is on a distinguished road
I tryed to use "getline();" but I get this error then:
Error: test.cpp(145,15):Call to undefined function 'getline'
 
 

Recent GIDBlogToyota - 2008 August Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Having problem in calling functions inthe main harsha C Programming Language 1 13-Oct-2004 00:05
Structure compilation problem nkhambal C Programming Language 1 03-Aug-2004 08:16
Problem after converting int to char ise152 C Programming Language 0 15-Jul-2004 23:03
(read/write file) newbie need help plz momotx C Programming Language 6 28-Jan-2004 13:40

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 19:21.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.