Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric input in C++ with trailing chars

Tags:

c++

double

cin

I need to fetch user input from std::cin into a variable of type double. This is in the context of complex numbers, so it often happens to have a number input as 5i or 5.4565i.

Consider the following code in the main() function:

while (true) {
    double c;
    std::cin >> c;
    std::cout << c << "\n\n";
}

Here's what happens:

In: 0.45
Out: 0.45
// OK

In: 5 0.45
Out: 5

0.45
// OK

In: 0.45i
Expected out: 0.45
Acutal out: 0

0

0...

I'm guessing this is because It's not recognizing 0.45i as a double. So how can I correctly fetch the value 0.45 from 0.45i, ignoring the trailing i?

like image 713
Sean Bone Avatar asked Aug 03 '26 03:08

Sean Bone


2 Answers

Read a string first and then convert to double,

$ cat ans.cpp 
#include <cstdlib>
#include <iostream>

int main()
{
    std::string str;
    double dbl;
    while (std::cin >> str) {
        dbl = std::strtod(str.data(), NULL);
        std::cout << dbl << std::endl;
    }
}

First you read each white space separated string into str. The strtod function will try to get as many as characters to form a floating point literate, including hex float. It returns the double parsed from this part of the string. The second parameter can be a char * pointer, which point to one pass the last character that is parsed. It is useful if you do not want to simply discard the trailing characters. It is ignored if it is null.

like image 178
Yan Zhou Avatar answered Aug 04 '26 20:08

Yan Zhou


You can test the state of the input string. If input has failed, just get the offending token in a string and proceed. For example:

double d;

for(;;) {
    std::string dummy;
    std::cout << "Input :";
    std::cin >> d;
    if (std::cin.fail()) {          // was input numeric?
        std::cin.clear();
        std::cin >> dummy;
        if (dummy == "END") break;  // out of the infinite loop...
        std::cout << "Non numeric: >" << dummy << "<" << std::endl;

    }
    else {
        std::cout << "Numeric: " << d << std::endl;
    }
}
like image 38
Serge Ballesta Avatar answered Aug 04 '26 20:08

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!