0

I'm trying to retreive from stdin two float numbers separated by characted "e" in C/C++.

The input is: 4.2e3

When I code

#include <cstdio>

int main(){
 float a, b;

  scanf("%fe%f", &a, &b);
  printf("%f %f", a, b);
  return 0;
}

I get 4200.000000 0.000000, but when I change character "e" both in input and in the code then I get 4.200000 3.000000 which is the expected result.

I solve this problem using string, split and casting but it is very unclean for me. There is the code I wrote

#include <iostream>
#include <bits/stdc++.h>
#include <boost/algorithm/string.hpp>
#include <string>

using namespace std;

int main(){
    float a, b;
    string line;
    vector<string> numbers;

    cin >> line;
    boost::split(numbers, line, boost::is_any_of("e"));
    a = strtod(numbers[0].c_str(), 0);
    b = strtod(numbers[1].c_str(), 0);

    printf("%f %f", a, b);
    return 0;
}

Is there a better way to solve this problem, especially faster way due to reading thousands of lines like this?

pistachio
  • 11
  • 1
  • First if you're using cin check out [Why is reading lines from stdin much slower in C++ than Python? - Stack Overflow](https://stackoverflow.com/questions/9371238/why-is-reading-lines-from-stdin-much-slower-in-c-than-python) – user202729 Mar 10 '19 at 09:41
  • Any reasons why you're using c-style `scanf()` input in preference of the `std::iomanip` facilities and `std::istream`? – πάντα ῥεῖ Mar 10 '19 at 09:41
  • I wonder, do you know that `4.2e3` or `4.2E3` is an accepted way to spell `4200`? It means 4.2 times ten raised to the power of three, "e" separating the exponent. The behaviour is thus fully correct (other than that you omit checking the returnvalue of `scanf()`). – Ulrich Eckhardt Mar 10 '19 at 09:45
  • If `e` is used for separating numbers, is there any other character used for scientific notation? – user202729 Mar 10 '19 at 09:45
  • @UlrichEckhardt It appears that OP knows that, but don't want to have this behavior. – user202729 Mar 10 '19 at 09:47
  • 1
    Because the existing code already works, the question may also be appropriate on [codereview.se]. – user202729 Mar 10 '19 at 09:54
  • @UlrichEckhardt Yes, I know that e or E is normally used for scientific-notation but here it is just characted separating two numbers. – pistachio Mar 10 '19 at 09:55
  • @user202729 no, i do not use any other characted for scientific notation because I do not needed one, all numbers have decimal point. – pistachio Mar 10 '19 at 09:59
  • There is https://stackoverflow.com/questions/7297623/how-to-provide-your-own-delimiter-for-cin, but you'd need to convert the string to a double/float later. – user202729 Mar 10 '19 at 10:03

0 Answers0