Thread: Quick input check question

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    21

    Quick input check question

    So I want to check to see if the command line argument I received was an integer. How do I do this?

    Code:
    #include <iostream>
    using namespace std;
    
    int main(int argc, char* argv[]) {
    	//**************************
    	//Checking for correct input
    	//**************************
    
    	if ( argc != 2 ) {
    		cerr << "Usage: " << argv[0] << " n" << endl;
    		return 1;
        }
    
    	if ( argv[1].isdigit() != 1 && ) {
    		cerr << "Usage: n must be a positive integer." << endl;
    		return 1;
    	}
    }
    However, the error message says that there is a request for member isdigit in *(argv + 4u) which is of nonclass type char*.

    I don't really understand the error message.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    isdigit is not a member function of anything, it's just a function. It also only works on a char, not a char*. The C way would be to use strtol (also not a member function) and pay attention to the second pointer argument to make sure it's at the end of the string. I don't know that there's much better in C++; boost's lexical_cast, maybe.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by tabstop View Post
    isdigit is not a member function of anything, it's just a function. It also only works on a char, not a char*. The C way would be to use strtol (also not a member function) and pay attention to the second pointer argument to make sure it's at the end of the string. I don't know that there's much better in C++; boost's lexical_cast, maybe.
    stringstream may be a solution that doesn't require the boost library.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Yes, thanks, I'm an idiot. (I'm pretty sure I've suggested that before, too; don't know why it didn't come to mind this time.)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. CIN Input count question?
    By kamran in forum C++ Programming
    Replies: 5
    Last Post: 10-24-2006, 04:06 PM
  3. Quick question
    By Rapt in forum C Programming
    Replies: 5
    Last Post: 11-01-2003, 02:16 AM
  4. * quick question *
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 03-27-2002, 06:58 PM