Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > C# and C > C++ and Visual C++ > C++ Programming
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
C++ Programming General discussions for the C++ language. For questions specific to Microsoft's Visual C++ variant, see the Visual C++ forum instead.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C++ Programming section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old August 22nd, 2004, 04:14 PM
Registered User
 
Join Date: Aug 2004
Location: Clunderwen, Pembrokeshire, United Kingdom.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Jakeyboy Send a message via Yahoo to Jakeyboy
Default C++ Beginner - help with input types

Hi, I'm new to this forum, so hi!

I'm a total beginner and I thought it would help my programming to write a program with a purpose, not just to say "hello world". As I'm good at Maths and have a good understanding of algebra, I thought I'd make a maths toolkit sort of thing...I'm taking it one step at a time, and i'm working on a simple converter for inches and centimetres. I've done the main part of the program (its console based at the moment, I need to learn some more windows programming before I venture there). The problem I have is, when there is a call for input (at the menu for instance, "enter 1 for this" etc.) if any key other than a number is pressed it skips to another part of the program and messes itself up. the only solution I've come up with is to write an If statement as such:

if (x!=1 || x!=2 || x!=3)
{
cout<<"Incorrect data type, please restart the program";
}

I've tried labelling the menu and then pointing it to that after a system("cls") to make it effectively restart, but it just screws itself again. also i can't use the above method of verification when the user is inputting a value for cm or inches. I'm using the Dev-C++ compiler from bloodshed (because its free!). My code is also really messy...I've put quotes at every possible chance...please don't get too angry, I'm doing my best to tidy it up a bit.

Ok, while writing this I tried to compile my code to check it was ok for posting and i now have 5 errors, saying that "cout" and "cin" etc are undeclared...whats going on? arg! maybe someone can help...

edit: fixed the minor errors with the code i think...still problems with input.



Code:
#include <iostream.h>
#include <stdlib.h>

float convertCmIn(float);
float convertInCm(float);
float main()


{
    float cm;     //  introducing the
    float inches; //  variables for cm and inches.
    float x;      //  "x" is the users choice of function
    menu:         
    cout<<"\t\tThe Centimetres/Inches conversion program, v0.1.2";
    cout<<"\n\n1. Convert Cm to Inches";   //choice 1
    cout<<"\n2. Convert Inches to Cm";     //choice 2
    cout<<"\n3. Exit";                     //choice 3
    cout<<"\n\nEnter your choice: ";       //users input here
    cin>>x;                                

   if (x==1)   //checks the users input,i.e. if the user put in "1"
       {          //do everything between the 2 brackets
       system("cls");
       cout<<"Enter a measurement in Centimetres to be converted to Inches: ";
       cin>>cm;    //the measurement in centimetres
       inches = convertCmIn(cm);   //calls the function to convert
       cout<<"\nHere's the measurement in inches: ";
       cout<< inches << endl;   //returns the value
       cout<< "\n\ncase1" << endl;
       system ("pause"); //"press any key to continue" (gives em a chance to view the output)
       system("cls"); //this clears the screen
       goto menu;    //go back to the menu
       }


   else if (x==2)  //see case one
       {
       system("cls");
       cout<<"Enter a measurement in inches to be converted to Centimetres: ";
          cin>>inches;

          cm = convertInCm(inches);

          cout<<"\nHere's the measurement in inches: ";
          cout<< cm << endl;
       cout<<"\n\ncase2" << endl;
       system ("pause");
       system("cls");
       goto menu;
       }


         else if (x==3)    //again, checking input
         return 0;         //return nothing, thereby ending the program (i think)

        else
        {
        cout<<"\n\n\tYour input was not valid, please restart the program\n\n";
        system("pause");
        return 0;                     //clear the screen.
        }

}

float convertCmIn(float cm)
      {
         float inches;
         inches = cm/2.54;
         return inches;

      }

float convertInCm(float inches)

      {
         float cm;
         cm = inches*2.54;
         return cm;

      }
      //end




Jakeyboy - Annoying Maths Teachers from the comfort of his caravan
Reply With Quote
  #2 (permalink)  
Old August 23rd, 2004, 12:45 AM
Authorized User
 
Join Date: Dec 2003
Location: Bristol, , United Kingdom.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Many compilers don't recognise cin and cout unless
you include stdio

#include <stdio.h>

Will probably solve that problem

maybe saying

if (x < 0 || x > 3)
would be neater but no better.

Good luck

Nokomis


Georges
Reply With Quote
  #3 (permalink)  
Old August 23rd, 2004, 09:44 AM
Authorized User
 
Join Date: Feb 2004
Location: , , .
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

What version dev-c++ are you using?

Mine (version 4.9.8.0) didn't compile correctly. The main() must be type int according to the c++ standard.

So change
Code:
float main()
to

Code:
int main()
cout and cin are part of the std namespace. Older versions of C++ didn't have namespaces, and using the headers that you have included gets around the namespace problem, but it is highly recommended, for now, that you use the following in stead of your #include statemsnts:
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
That should make your program ok to compile with any C++ compiler that complies with the C++ standard.

Now as for your logic:

You could use

Code:
if ((x != 1) && (x != 2) && (x != 3))
Think about the logic, and put it into words.

You want to continue if

(x is equal to 1) or (x is equal to 2) or (x is equal to 3)

That means you want to quit if

(x is not equal to 1) and (x is not equal to 2) and (x is not equal to 3)

You will be making this kind of decision many times in your life (including in programs).

Formally, the equivalence between the two above statements is known as DeMorgans Rule (from DeMorgans Theorem).

Good Luck

Dave
Reply With Quote
  #4 (permalink)  
Old August 23rd, 2004, 02:26 PM
Registered User
 
Join Date: Aug 2004
Location: Clunderwen, Pembrokeshire, United Kingdom.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to Jakeyboy Send a message via Yahoo to Jakeyboy
Default

Thanks Dave, thats solved the first choice part, is there anyway of making it so I can return it to the beginning of the program if x isn't 1/2/3? Also what can I do about the entering of measurements in the rest of the program? for instance, if someone puts in an alphabet character instead of a number? I've tried using <65536 sort of checks, but then a characteer seems to be recognised as a value...is there any form of checking the type of input? By the way, I'm using version 4, but im gonna start the new update in a while *kicks 56k modem*.

Thanks alo for your help!

Jake

Jakeyboy - Annoying Maths Teachers from the comfort of his caravan
Reply With Quote
  #5 (permalink)  
Old August 23rd, 2004, 03:39 PM
Friend of Wrox
 
Join Date: Jul 2004
Location: Tehran, , Iran.
Posts: 623
Thanks: 0
Thanked 1 Time in 1 Post
Default

sorry for my delay
(some points from logic)
(x!=1 || x!=2 || x!=3) is always true because
(x!=1 || x!=2 || x!=3)==![(x=1)&(x=2)&(x=3)]==!false==true
about checking your input why you want to restart your program everytime you can
skip wrong inputs until you get a valid input,you should do it something like below
Code:
char a;
a=getch();
while((a<'0')||( a>'9'))
{
a=getch();
}
//here a has a valid input
Hope I got your meaning correctly.
HtH.

--------------------------------------------
Mehdi.:)
Reply With Quote
  #6 (permalink)  
Old August 23rd, 2004, 08:01 PM
Authorized User
 
Join Date: Feb 2004
Location: , , .
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

The way to protect against bad user input is to use cin.getline() to input the entire command line as a string. Then you can check to see if the character(s) that the user entered is (are) valid. Read up on how to use getline().

As for the logic for using the input, consider a switch{}. For more than one or two choices, switch{} is usually cleaner than deeply nested if statemennts.

So, let's say you have determined that the first user character is in a char variable named, say, "cmnd_char"



Code:
  switch(cmnd_char) {

    case '1': // Here are the actions for user input '1'
                ...
              //
              break;

    case '2': //
                ...
              //
              break;

    case '3': // Here are the actions for user input '2'
                ...
              //
              break;
 
    default: // Here is the stuff for invalid input.
               ...
             //
  }

Regards,

Dave
Reply With Quote
  #7 (permalink)  
Old August 24th, 2004, 12:24 AM
Authorized User
 
Join Date: Dec 2003
Location: Bristol, , United Kingdom.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Some compilers don't like the inverted commas
shown in that example. If you have a problem with it
try:

switch(value)
{
     case 1:
            dothis();
            dothat();
            break;
     case 2:
            dotheother();
            break;
     default:
            donothing();
}

remember to put in the break command or
it will run on from case one to case two etc!

Nokomis




Georges
Reply With Quote
  #8 (permalink)  
Old August 24th, 2004, 01:15 AM
Friend of Wrox
 
Join Date: Jul 2004
Location: Tehran, , Iran.
Posts: 623
Thanks: 0
Thanked 1 Time in 1 Post
Default

nokomis,they are char variables not integer variables so it works fine.
if I were you I didnt use getline(),when you want to handle only one character why using getline()!
the bestway is reading invalid characters until getting a valid character then using switch you can determine what action should be done according your valid inputs.


--------------------------------------------
Mehdi.:)
Reply With Quote
  #9 (permalink)  
Old August 24th, 2004, 02:03 AM
Authorized User
 
Join Date: Dec 2003
Location: Bristol, , United Kingdom.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

OK! Just so! 'a' etc fine in that sense!

Why bother with the complexities of cin, cout, getline and that stuff when gets(), and all the printf() and scanf() procedures are there to help?

Georges
Reply With Quote
  #10 (permalink)  
Old August 24th, 2004, 08:46 AM
Authorized User
 
Join Date: Feb 2004
Location: , , .
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:Originally posted by nokomis
 OK! Just so! 'a' etc fine in that sense!

Why bother with the complexities of cin, cout, getline and that stuff when gets(), and all the printf() and scanf() procedures are there to help?

Georges
When learning C++, I think it is entirely appropriate to deal with cin, cout, getline, etc. The "old-fashioned" C-style ways still work, but lots of powerful tools become available if you learn about C++ functions (use of C++ strings, for example).

By the way, use fgets(), not gets(), to make sure you don't overflow whatever input buffer you are using.

Also, note that for example 'a' evaluates to an integer value of 97 (decimal) and can be used any place that an int variable is legal.

try this:
Code:
#include <stdio.h>
int main()
{
  int x;
  char y;

  for (x = 'a'; x <= 'd'; x++) {
    switch (x) {
      case 'a': printf("x = 0x%02x (%d decimal)\n", x, x);
                break;

      case 'b': printf("x = '%c'  (%d decimal, 0x%02x hex)\n", x, x, x);
                break;

      default : printf("x = %3d  (0x%02x hex)\n", x, x);
    }
  }
  y = x;

  printf("y = '%c'  (%d decimal)\n", y, y);
  return 0;
}
Note that this is a valid C program and a valid C++ program.

Dave

Dave
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

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

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Variable types lowell VB.NET 3 July 24th, 2007 12:53 AM
Types DARSIN Oracle 2 February 5th, 2005 12:14 AM
Data Types bph Access VBA 3 January 25th, 2004 05:50 PM



All times are GMT -4. The time now is 09:16 AM.


Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.