Thread: error checking

  1. #1
    Unregistered
    Guest

    error checking

    Hi, I am a high school student taking C++.

    I had to write a program which takes in a number and lists all of the primes less than or equal to that number.

    That I did no problem.

    Now the teacher would like us to check the input to be sure that it is allowable.

    I have read the FAQ and still don't understand how to take in a string (C++ style) and convert it to an int. Could someone help.

    Or is that the best way to do it??

    string user_input;
    cout << "Please enter a positive integer: ( 0 to quit )";
    cin >> user_input;

    So I need to be sure that the user has entered a positive integer or 0. If 0 then quit. If not a positive int then I need to ask again.

    We have not covered pointers yet so I don't know how to use them. Any help or a link to a place that could help would be much appreciated.

  2. #2
    Programming is fun, mkay?
    Join Date
    Oct 2001
    Posts
    490

    Lightbulb here you go...

    Use atoi(). I am not sure which .h file, though:


    If(atoi(user_input) <= 0)
    {
    cout << "Not a positive number!\n\n";
    return 0;
    }
    else
    {
    // Do stuff because it is allowable
    }
    Website(s): http://www16.brinkster.com/trifaze/

    E-mail: [email protected]

    ---------------------------------
    C++ Environment: MSVC++ 6.0; Dev-C++ 4.0/4.1
    DirectX Version: 9.0b
    DX SDK: DirectX 8.1 SDK

  3. #3
    Unregistered
    Guest
    Hi I appreciate the response!

    When I tried to compile, I got the following error:

    cannot convert `user_input' from type `string' to type `const char *'

    with the line number with the atoi function on it.

    This is the same problems I was having when trying to implement it.

    I thought that you can not use atoi on a C++ string, and that it only works on C style strings. But I am having trouble with that as well.

    Thanks

  4. #4
    Programming is fun, mkay?
    Join Date
    Oct 2001
    Posts
    490

    Lightbulb You have to...

    You have to change:

    string user_input

    to:

    char user_input[1000];
    Website(s): http://www16.brinkster.com/trifaze/

    E-mail: [email protected]

    ---------------------------------
    C++ Environment: MSVC++ 6.0; Dev-C++ 4.0/4.1
    DirectX Version: 9.0b
    DX SDK: DirectX 8.1 SDK

  5. #5
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    or use atoi(user_input.c_str()) which will allow you to use the string class
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed