C++ character to int

前端 未结 5 1702
梦谈多话
梦谈多话 2020-12-11 16:36

what happens when you cin>> letter to int variable? I tried simple code to add 2 int numbers, first read them, than add them. But when I enter letter, it just fails and prin

5条回答
  •  既然无缘
    2020-12-11 17:16

    When you are doing something like:

    int x;
    cin >> x;
    

    You are instructing C++ to expect to read an int from keyboard. Actually, when you enter something not an int, the input stream (standard input, in this case) renders unusable due to its error state.

    That's why I personally prefer to always read strings, and convert them to numbers if needed. There are conversion functions in the C part of the C++ standard library that can help with this.

    double cnvtToNumber(const std::string &num)
    {
        char * ptr;
        double toret = strtod( num.c_str(), &ptr );
    
        if ( *ptr != 0 ) { // If it got to the end of the string, then it is correct.
            throw std::runtime_error( "input was not a number" );
        }
        return toret;
    }
    

    Here you are converting a number, and detecting if the conversion was right. strtod(s) will only stop when finding the end of the string, or a space. In order to avoid trailing spaces fooling the function, you could need a trim function:

    std::string &trim(std::string &str)
    {
        // Remove trailing spaces
        unsigned int pos = str.length() -1;
    
        while( str[ pos ] == ' ' ) {
            --pos;
        }
    
        if ( pos < ( str.length() -1 ) ) {
            str.erase( pos + 1 );
        }
    
        // Remove spaces at the beginning
        pos = 0;
        while( str[ pos ] == ' ' ) {
            ++pos;
        }
    
        if ( pos < 1 ) {
            str.erase( 0, pos );
        }
    
        return str;
    }
    

    Now you can safely read from console (or whatever other input stream):

    int main()
    {
        std::string entry;
    
        try {
            std::getline( std::cin, entry );
            int age = cnvtToNumber( trim( entry ) );
    
            std::cout << age << std::endl;
        } catch(const std::exception &e) {
            std::cerr << e.what() << std::endl;
        }
    }
    

    Of course you can lose precision if you always read double's and then convert them. There are specific functions for integers (strtol(s)), in case you want to investigate further.

提交回复
热议问题