如何为istream / istringstream使用'fixed'flolandfield? [英] How to use 'fixed' floatfield for istream/istringstream?

查看:157
本文介绍了如何为istream / istringstream使用'fixed'flolandfield?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++有一个名为fixed的I / O操纵器,以固定(非科学)形式输入/输出浮点数。它适用于输出,但我不明白如何使输入正常工作。

C++ has an I/O manipulator called 'fixed' to input/output floating-point numbers in fixed (non-scientific) form. It works fine for output, but I don't understand how to get input working properly.

考虑这个例子:

#include <sstream>
#include <iostream>
using namespace std;

int main() {
    double value;
    istringstream("1.4e1") >> fixed >> value;
    cout << value << endl;
}

在我看来,它应该像这样工作。输入流有一些字符串。当我们对它应用 fixed 操纵器并尝试读取double / float时,它应该停在第一个不是数字或点的字符上(不接受点) /第三次/更多次)。因此,正确的输出将是 1.4 (当我们遇到'e'时,我们会停止处理输入。)

In my opinion, it should work like this. Input stream has some string. When we apply fixed manipulator on it and try to read a double/float, it should stop on a first character which is not a digit or a dot (dot is not accepted second/third/more times). So, correct output would be 1.4 (we stop processing input when we encounter 'e').

相反,此代码输出 14 。为什么?它是如何工作的,输入流的固定的目的是什么?如何读取输入流中的double并停在'e'(将其保留在输入流中)?

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

推荐答案


我需要读取一个值 1.4 ,留下 e 。是否有可能?

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

没有标准的操纵器,我相信有一种定义自定义操纵器的方法,但是这太复杂了。我还没有找到关于如何在SO上做到这一点的答案,我只找到了关于输出流修改器的问题

There isn't a standard manipulator for this, I believe that there's a way to define a custom ones, but it would be too complex. I haven't found an answer on how to do that here on SO, I have only found a question about output stream modifier.

让我们转向至少某种解决方案。那将是你自己解析:

Let's move to at least some kind of solution. That would be parsing it yourself:

#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;
}

这篇关于如何为istream / istringstream使用'fixed'flolandfield?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆