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?
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With