How to detect negative numbers as parsing errors when reading unsigned integers?

后端 未结 3 674
别跟我提以往
别跟我提以往 2020-12-03 21:33

I want to read unsigned integers in base-10 (decimal) representation from a C++ iostream with at least rudimentary error detection. In my view, minus signs would clearly be

3条回答
  •  醉梦人生
    2020-12-03 22:29

    Would it be really different if you'd done this?

    int i;
    unsigned int u;
    c >> i;
    u = i;
    std :: cout << u;
    

    It doesn't matter so much that operator>> tolerates the sign mismatch because the underlying C rules will allow a silent conversion in any case. You're not fundamentally adding any safety by "strengthening" the input operator.

    That said, my gcc (4.3.5 on Solaris) says it's a conversion error.

提交回复
热议问题