validation

This is a discussion on validation within the C++ Programming forums, part of the General Programming Boards category; Hello, I'm Ide Swager from Holland. I just started programming in C++ but I'm pretty experienced in PHP. I made ...

  1. #1
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312

    Question validation

    Hello,

    I'm Ide Swager from Holland.

    I just started programming in C++ but I'm pretty experienced in PHP.
    I made a calculator, he worked perfect until I wanted a validation (to check if the user inserts letters instead of numbers)

    I have made this code:

    Code:
    if (typeid(number1).name() == "double" && typeid(number2).name() == "double")
    {
        \\ rest of script
    }
    else
    {
        cout << "ERROR" << endl;
    }
    The number1 and number2 are doubles! (I checked it with cout << typeid(number1).name(); )

    And it keeps saying ERROR!
    Can you guys help me out?

  2. #2
    Tropical Coder Darryl's Avatar
    Join Date
    Mar 2005
    Location
    Cayman Islands
    Posts
    503
    what compiler... what's the error.

    psychic suggestion, did you enable RTTI in your compiler?

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    If you have
    double var;

    And you do something like
    cin >> var;

    Then typing in "hello world" will NOT change the type of var - that's fixed by the compiler.

    You need a whole new approach to validating user input.

  4. #4
    Registered User
    Join Date
    Jan 2006
    Posts
    63
    isalpha() function, that is a good start for what you need.

  5. #5
    60% Braindead
    Join Date
    Dec 2005
    Posts
    379
    Cycle through some characters and see if they are valid.

    An example is always good:

    Code:
    char validate(char c) {
    #define UMAPLENGTH 3;
    char UMAP[] = "123";
    int x;
    
     for(x=0; x < UMAPLENGTH; x++)
      if(c == UMAP[x])
       return c;
    
    return 0;
    }
    This cycles through a list, in this case 1, 2, and 3. If your char is 1, 2, or 3, they will be returned normaly. Otherwise, they will be returned as a null character.
    Code:
    Error W8057 C:\\Life.cpp: Invalid number of arguments in function run(Brain *)

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    The easy way to do input validation is to check the return value of the read. If you are dooing input with cin >>, then just check the return value:
    Code:
    while (!(std::cin >> number1))
    {
      std::cin.clear()
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      // Re-prompt.
    }
    You have to #include <limits> to use numeric_limits, or you can use any large number instead.

    Validating character by character and using isalpha are extra work that isn't necessary when the functionality is built in to input streams.
    Last edited by Daved; 01-26-2006 at 11:38 AM.

  7. #7
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    I already tried isdigit() but that only works on char. And thanks for all the help!

  8. #8
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    My compiler is Borland. There's no error and I don't know what RTTI is :P I'm not far yet.

  9. #9
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Your main problem is that you think C++ has the same weak typing as PHP. But C++ has strong typing: a variable is declared with a type and keeps it forever.

    You can't compare strings with ==, unless you use the std::string class.

    cin doesn't read invalid values into a double in the first place - but it goes into an error state if it can't read correct input, which you have to solve.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    2,662
    1) As Salem pointed out, what you are trying to do--even if it did work--would not properly validate the input. The type of a variable does not change, so checking its type does not in any way indicate what type of data the user entered.

    2)
    I just started programming in C++ but I'm pretty experienced in PHP.
    C++ ain't PHP.

    Examine the output from this program:
    Code:
    #include <iostream>
    using namespace std;
    
    int main ()
    {
    
    	//Pointer to an array of characters(an array of characters is known
    	//as a c-style string):
    	
    	char str[] = "double";
    	const char* myPointer = str; //assigns the address of str to myPointer
    
    	if(myPointer == "double") 
    	{
    		cout<<"yes"<<endl;
    	}
    	else
    	{
    		cout<<"no"<<endl;
    	}
    
    	//Pointer to a string literal:
    
    	const char* myOtherPointer = "double";
    	if(myOtherPointer == "double") 
    	{
    		cout<<"yes"<<endl;
    	}
    	else
    	{
    		cout<<"no"<<endl;
    	}
    
    
    	return 0;
    
    }
    The reason for the different output has to do with the differences between pointers, character arrays, and how C++ handles string literals(i.e. anything between double quotes), like "double".

    In C++, whenever you have a string literal, e.g. "double", on the right side of an equals sign, the compiler takes the string literal, slaps a '\0' character on the end of it and stores it in memory somewhere, and then returns its address. For instance, if you do this:

    Code:
    const char* myPointer = "double";
    then myPointer is assigned the address in memory where the compiler stored the string "double\0". Additionally, the compiler only stores the string literal "double" in memory the first time it is encountered. Subsequently, when the compiler sees "double" again, it just returns the address where it first stored "double" in memory.

    Now, depending on what's on the other side of the equals sign opposite the string literal, different things happen. When a char array is on the left side of the equals sign, e.g.

    Code:
    char str[] = "double";
    The compiler goes to the memory location where "double\0" is stored and copies it character by character to a new memory location and names it "str". Then, if you try to compare str to "double" with ==, you are actually comparing the addresses of str and "double\0", and since they are at two different addresses in memory, the addresses aren't equal. To compare the values at those addresses, rather than the addresses themselves, you have to use the strcmp() function.

    On the other hand, when you have a pointer variable on the left side of the equals sign opposite the string literal, e.g.

    const char* myOtherPointer = "double";

    the address of "double\0" is assigned to myOtherPointer. So, if you subsequently compare myOtherPointer to "double" using ==, you will once again compare addresses, but this time they will be equal.

    Because of the "erroneous" output you are seeing in your program, it is apparent to me that the name() function must be returning a pointer to a char array containing "double" rather than a pointer directly to the string literal "double".

    You will constantly get tripped up by things like that in C++ until you gain a lot more experience.
    Last edited by 7stud; 01-28-2006 at 10:46 AM.

  11. #11
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    I used daved's code and it works! , but 1 more thing: I have this code:

    Code:
    while (!(std::cin >> number1))
              {
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                cout << "error has occured.";
                system("cls");
              }
    I expected system("cls"); would exit the program! But it doesn't: the while loop continues! How can I abort the program?

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    If you are in main(), just return 0 or return 1 or whatever you want to return (0 usually means success, so you would use something non-zero, but most people don't really use their program's return value anyway).

    If you are in a separate function, you can use exit(0) or exit(1) or whatever, or you can return from your function some value or exception to indicate that the function failed so that the calling code can handle it and exit the program correctly.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. validation of TextBoxes!?
    By c9dw2rm8 in forum C# Programming
    Replies: 1
    Last Post: 04-01-2008, 06:19 PM
  2. set validation
    By jmarsh56 in forum C++ Programming
    Replies: 4
    Last Post: 12-13-2005, 07:49 AM
  3. DATE <TIME.H> data validation
    By bazzano in forum C Programming
    Replies: 4
    Last Post: 08-07-2005, 01:10 AM
  4. validation routine help plz
    By rajesh23 in forum C Programming
    Replies: 8
    Last Post: 09-23-2003, 07:21 AM
  5. [C#] Validation class for events?
    By gicio in forum C# Programming
    Replies: 4
    Last Post: 01-03-2003, 11:19 AM

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