Reading errors in floats

This is a discussion on Reading errors in floats within the C++ Programming forums, part of the General Programming Boards category; The goal is to write program asking for the user for a float, and to put in safety nets against ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    5

    Reading errors in floats

    The goal is to write program asking for the user for a float, and to put in safety nets against in-proper entries.
    The following code allows the user to enter both positive and negative integers and floats, but the program won't give the error message for certain types of input errors.
    92.64.47 will be displayed as 92.64
    864hj will be displayed as 864.
    Whenever the code reaches an error in having the input be an integer or float, it doesn't give an error message, it just stops the string right there.
    Suggestions on where/what my problem is and how I might fix it?

    Code:
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    int main()
    {
    	float myFloat;
    	char myStr[30];
    	bool validData;
    	int i, len /* length of string */;
    
    	do
    	{
    		cout << "Enter a float number: ";
    		cin.getline(myStr,30);
    
    		validData = true;
    			len = strlen(myStr);
    		i=0;
    
    
    		while ((i < len) && (validData == true))
    		{
    
    			if ((i == 0) && ((myStr[i] < '0') || (myStr[i] > '9')) && (myStr[i] != '-') && (myStr[i] != '.'))  //allows for +- integers and floats
    			{
    					cout << "if loop checking\n";
    					validData = false;
    					cout << "if loop checked\n";
    			}
    
    
    			
    			i++;
    		}
    
    		if (validData == true)
    		{
    			myFloat = atof(myStr);
    			cout << "Your float is: " << myFloat << "\n";
    		}
    		
    		else
    		{
    			cout << "Incorrect Data. Try again!!!\n";
    		}
    	} while (validData == false);
    
    	return 0;
    }

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,069
    This is C++ not C. ...and your problem is, that's how cin works. It starts from the beginning and gets all the pertainent data it can. Then it stops. If it doesn't get anything, it fails.

    Read in as a string then use string streams to convert to whatever you want. Voila.
    Sent from my iPadŽ

  3. #3
    Registered User
    Join Date
    Mar 2006
    Posts
    5
    By bad on the wrong forum, duly noted for any future problems.
    Thanks for the quick reply.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,541
    http://www.hmug.org/man/3/strtod.php

    Code:
    cin.getline(myStr,30);
    char *end;
    double d = strtod ( myStr, &end );
    if ( end == myStr ) {
      // nothing converted
    } else
    if ( errno == ERANGE ) {
      // over/under flow
    } else
    if ( *end != '\0' && !isspace(*end) ) {
      // some garbage at end of string
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,318
    Code:
    float myFloat;
    cout << "Enter a float number: ";
    while (!(cin >> myFloat) || cin.get() != '\n')
    {
      cin.clear();
      cin.ignore(1000, '\n');
      cout << "Incorrect Data. Try again!!!\nEnter a float number: ";
    }
    cout << "Your float is: " << myFloat << "\n";
    Search through some of my recent posts for explanations on why it is that simple.

  6. #6
    Registered User
    Join Date
    Mar 2006
    Posts
    5
    That does work, thank you. However, this is a homework assignment that requires the use of strings so I don't think I can use yours.

  7. #7
    Registered User
    Join Date
    Mar 2006
    Posts
    5
    I've been going through my book (unfortunatly the lectures have a habbit of not covering everything you need for the assignments, I guess that's one way to challenge you), and one example shows the program using
    Code:
    getline( cin, string)
    Yet when I go from
    Code:
    cin.getline(myStr,30)
    to
    Code:
    getline( cin, myStr)
    I get an error.

    note: <string> library is now included

  8. #8
    Registered User
    Join Date
    Mar 2006
    Posts
    5
    More stuff. I'm trying to just expand my if statement to enclude everything.

    Code:
    if (((myStr[i] < '0') || (myStr[i] > '9')) //allows only digits 0-9 in the string
    				&& ((myStr[i] != '-') && (myStr[0] = '-')) //allows -'s in the string
    				&& (myStr[i] != '.'))//allows decimal points in the string
    There is a problem in second and third line (tho I haven't even begun working the third line). What I want it to be read as is "- signs are okay, but only in the first spot, otherwise, bad code."

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,318
    cin.getline(myStr,30) is for use with C style strings like myStr in your original code. getline( cin, myStr) is for C++ strings. You'd have to declare myStr as string myStr; instead of as a character array. You should prefer C++ strings in C++ programs, but unfortunately some classes require you to use C style strings instead. Whichever type of string you use determines which type of getline you use.

    >> (myStr[0] = '-')

    That is wrong because youuse = instead of ==. But a better way to do it would be to check if i does not equal 0 before checking whether myStr[i] is '-'.
    Last edited by Daved; 03-21-2006 at 02:22 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Header File Errors...
    By Junior89 in forum C++ Programming
    Replies: 5
    Last Post: 07-08-2007, 12:28 AM
  2. Script errors - bool unrecognized and struct issues
    By ulillillia in forum Windows Programming
    Replies: 10
    Last Post: 12-18-2006, 03:44 AM
  3. Sneaky little linker errors...
    By Tozar in forum C++ Programming
    Replies: 8
    Last Post: 10-25-2006, 05:40 AM
  4. executing errors
    By s0ul2squeeze in forum C++ Programming
    Replies: 3
    Last Post: 03-26-2002, 12:43 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21