1

I do the following:

float f;
cin >> f;

On the string:

0.123W

Number 0.123 will be properly read to f, and stream reading will be stopped on 'W'. But if we enter:

0.123E

operation will fail and cin.fail() will return true. Probably the trailing 'E' will be treated as part of scientific notation.

I've tried cin.unsetf(std::ios::scientific); with no success.

Is there any possibility to disable treating character 'E' specially?

peper0
  • 3,111
  • 23
  • 35
  • Have you tried std::cin.ignore ? – Marco A. Feb 07 '14 at 15:04
  • My intention is to read a floating point number successfully and leave 'E' character for further reading. What is point of using ignore here? – peper0 Feb 07 '14 at 15:08
  • 1
    At least on Mac OS X, the C language standard I/O facilities accept the `0.123E` notation as being a floating point number 0.123 followed by an unused letter E. That suggests that one option is to use that, though it is not nice given that you're working in C++. Working in C++ (`g++` 4.8.2), I get the error. This suggests that the C++ standard requires the error, unlike the C standard — though from a C programmer's perspective, that seems like broken behaviour — both `0.123E` and `0.123E-` should be OK, stopping at the E. – Jonathan Leffler Feb 07 '14 at 15:20
  • 1
    Nitpick: it's not a *leading*, it's a *trailing* `e`. – rustyx Sep 17 '20 at 10:24

2 Answers2

2

You'll need to read the value as a string, and parse it yourself.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

Yes, you have to parse it your self. Here is some code:

// Note: Requires C++11
#include <string>
#include <algorithm>
#include <stdexcept>
#include <cctype>
using namespace std;

float string_to_float (const string& str)
{
    size_t pos;
    float value = stof (str, &pos);
    // Check if whole string is used. Only allow extra chars if isblank()
    if (pos != str.length()) {
        if (not all_of (str.cbegin()+pos, str.cend(), isblank))
            throw invalid_argument ("string_to_float: extra characters");
    }
    return value;
}

Usage:

#include <iostream>
string str;
if (cin >> str) {
    float val = string_to_float (str);
    cout << "Got " << val << "\n";
} else cerr << "cin error!\n"; // or eof?