Strange BUG in C++ iostream?

给你一囗甜甜゛ 提交于 2019-12-02 02:55:28

问题


is this a bug in iostream? ...

        #include<iostream>
        void money_conversion (){

        constexpr double dollars_in_yen=0.01;
        constexpr double dollars_in_euro=1.16;
        constexpr double dollars_in_pound=1.33;
        std::cout<<"Supported valutes : yen ('y'), euros('e'), pounds('p').\n";
        std::cout<<"Please enter the value + valute that you want to convert into dollars! :";
        double value=1;
        char valute=0;
        while(true){
        std::cin>>value>>valute;
        if(valute=='y')
            std::cout<<"\n\n"<<value<<" yens is "<<value*dollars_in_yen<<" dollars. \n";
        else if(valute=='e')
            std::cout<<"\n\n"<<value<<" euros is "<<value*dollars_in_euro<<" dollars. \n";
        else if(valute=='p')
            std::cout<<"\n\n"<<value<<" pounds is "<<value*dollars_in_pound<<" dollars. \n";
        else
            std::cout<<"\n\nSorry, unknown valute ("<<valute<<").\n";
        }

    }


    int main(){

        money_conversion();
        return 0;

    }

When keyboard input is

  • '5p' or

  • '5 p' or

  • '3y' or

  • '3 y' or

  • '1 z' or

  • 1z' or

  • '10 e'

everything goes as expected.

When the input is '(anyting)e' its an error (like '5e') I have tryied pretty much everything to try to make it work but no success.

When i remove while() loop i get this output when entered '5e' -> "Sorry, unknown valute ( )" but when i enter lets say '7m' i get output "Sorry, unknown valute (m)."

I make of this a big deal because, in large code, this can be an error that is almost impossible to notice. Is 'e' a problem as char input in some cases?


回答1:


No, this is not a bug in the C++ stream classes.

You need to read in the input as a std::string and extract the value and the currency yourself.

That's because e is used to separate the significand and the exponent in scientific notation, which is another way of specifying a double. Threfore 10e is an invalid double as it's missing the portion that defines the exponent.

By the way, using GBP, EUR, and JPY (which are the ISO codes for the currencies you want to support) would be less idiosyncratic.




回答2:


When a std::istream or std::locale library function attempts to parse any numeric input, it always first grabs all contiguous characters in the set "0123456789abcdefxABCDEFX+-" and which might be valid for the type of conversion being done, and only then tries to determine what they mean. See the description of Stage 2 of the num_get processing.

So in your "5e" example, the operator>>(double&) function grabs both '5' and 'e', expecting to find an exponent after the 'e', but stops there, and those characters don't make a valid complete double.



来源:https://stackoverflow.com/questions/47072240/strange-bug-in-c-iostream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!