Created
April 27, 2022 13:39
-
-
Save Vftdan/9a4bff4df412b39d925b4c4120bcc357 to your computer and use it in GitHub Desktop.
Comparison of float parsing with istream & other methods in native & emscriptens compilers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <cstdlib> | |
#include <locale> | |
using namespace std; | |
int main() { | |
string s = "23.4f"; | |
stringstream stream(s); | |
float f; | |
char c; | |
cout << "Flags = " << stream.flags() << endl; | |
cout << "Using locale " << stream.getloc().name() << endl; | |
stream >> f; | |
stream.get(c); | |
cout << endl << "istream:" << endl; | |
cout << "Float = " << f << endl << "Character = " << c << endl; | |
stringstream stream2(s); | |
auto loc = stream2.getloc(); | |
auto& ng = use_facet<num_get<char, istreambuf_iterator<char>>>(loc); | |
istreambuf_iterator<char> beg{stream2}, end; | |
ios::iostate state = {}; | |
f = 0; | |
ng.get(beg, end, stream2, state, f); | |
cout << endl << "num_get:" << endl; | |
cout << "Float = " << f << endl << "state = " << state << endl; | |
char* endptr = NULL; | |
f = strtof(s.c_str(), &endptr); | |
cout << endl << "strtof:" << endl; | |
cout << "Float = " << f << endl; | |
if (endptr == NULL) | |
cout << "Endptr is NULL" << endl; | |
else | |
cout << "Endptr is shifted by " << endptr - s.c_str() << endl; | |
cout << endl << "sscanf:" << endl; | |
f = 0; | |
int chars_consumed = 0; | |
sscanf(s.c_str(), "%g%n", &f, &chars_consumed); | |
cout << "Float = " << f << endl << "# of consumed characters = " << chars_consumed << endl; | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
run: main main.js | |
@echo "=== Native ===" | |
./main | |
@echo | |
@echo "=== Emscripten ===" | |
node ./main.js | |
main: main.cpp | |
g++ -std=c++11 main.cpp -o main | |
main.js: main.cpp | |
em++ -std=c++11 main.cpp -o main.js | |
.PHONY: run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment