emscripten icon indicating copy to clipboard operation
emscripten copied to clipboard

stringstream acts incorrectly with double type value when some characters are followed

Open hly2019 opened this issue 1 year ago • 0 comments

Please include the following in your bug report:

Version of emscripten/emsdk: 3.1.54

Failing command line in full: Hi, it seems when we use C++ stringstream to copy double values, it fails if the number is followed by characters, like "1a" or "1n".

This happened when I tried to port a project muparser to Wasm. The code example could be seen as follows.

I also found a quite related issue: https://github.com/beltoforion/muparser/issues/123 on MacOS, in which it describe quite similar behavior as I meet when compiling with Emscripten. The issue also points to a bug of LLVM here: https://github.com/llvm/llvm-project/issues/18156.

I'm wondering if the similar behavior with Emscripten is also caused by that issue of LLVM?

Thank you!

Code

#include <iostream>
#include <sstream>
#include <string>

typedef std::string string_type;
typedef string_type::value_type char_type;
typedef std::basic_stringstream<char_type, std::char_traits<char_type>, std::allocator<char_type> > stringstream_type;

int IsVal(const char_type* str, double* val) {
    double temp_val(0);
    std::cout << "input str: " << str << std::endl;
    stringstream_type stream(str);
    stream >> temp_val;
    std::cout << "fVal: " << temp_val << std::endl;
    stringstream_type::pos_type end = stream.tellg();
    std::cout << "iEnd is: " << end << std::endl;
    if (end == -1) {
        return 0;
    }
    *val = temp_val;
    return 1;
}

int main() {
    double num_value;
    std::string num_expr = "1n";
    int isval = IsVal(num_expr.c_str(), &num_value);
    if (isval) {
        std::cout << "Parsed value: " << num_value << std::endl;
    } else {
        std::cout << "Failed to parse value." << std::endl;
    }
    
    return 0;
}

Results

Expect to get the value 1, but failed in Wasm

# with emscripten
$ emcc test_stream.cpp -o main.js; node main.js
input str: 1n
fVal: 0
iEnd is: -1
Failed to parse value.

# with gcc
$ g++ test_stream.cpp -o main; ./main
input str: 1n
fVal: 1
iEnd is: 1
Parsed value: 1

hly2019 avatar Jul 30 '24 05:07 hly2019