How to use 'fixed' floatfield for istream / istringstream?

C ++ has an I / O manipulator called “fixed” for I / O floating point numbers in a fixed (unscientific) form. It works great for output, but I don’t understand how to enter input correctly.

Consider the following example:

#include <sstream> #include <iostream> using namespace std; int main() { double value; istringstream("1.4e1") >> fixed >> value; cout << value << endl; } 

In my opinion, this should work like this. The input stream has some string. When we use the fixed manipulator on it and try to read double / float, it should stop at the first character, which is not a digit or a point (the point is not accepted second / third / more). Thus, the correct output will be 1.4 (we stop processing input when we encounter 'e' ).

Instead, this code outputs 14 . What for? How does it work and what is the fixed purpose for input streams? How can I read the double input stream and stop at 'e' (leave it in the input stream)?

+6
source share
3 answers

You should use std :: scientific. I tried like this:

 #include <sstream> #include <iostream> using namespace std; int main() { double value; cin >> std::fixed>> std::scientific >> value; cout << std::scientific<<value << endl; } 

: 1.4e1 output: 1.400000e + 01

0
source

This question is somewhat misleading. 1.4e1 = 1.4 * 10¹ = 1.4 * 10 = 14 .

[...] he must stop at the first character, which is not a digit or a point (the point is not accepted a second / third / more times).

Why? e1 in 1.4e1 is part of a number: without it, the value is different. You must read it if you want to parse it correctly.

So, the correct result will be 1.4 (we stop processing input when we meet "e").

This is applicable if you are reading an integral type that “stops” parsing, if a character without a digit is encountered ([0-9]), or other conditions (for example, overflow or downstream) are triggered.

0
source

I need to read the value as 1.4 , leaving e in the input stream. Is it possible?

There is no standard manipulator for this, I believe that there is a way to define custom ones, but it will be too complicated. I did not find an answer on how to do this here, SO, I found a question about the output stream modifier .

Go to at least some solution. This will be on its own:

 #include <iostream> #include <sstream> #include <string> #include <cctype> int main() { std::istringstream iss("1.4e1"); double value; { std::string s; while(iss.peek() != 'e' && !std::isspace(iss.peek())) s.push_back(iss.get()); std::istringstream(s) >> value; } std::cout << value << std::endl; } 
0
source

Source: https://habr.com/ru/post/985202/


All Articles