What does it mean when a C++ program prints the following number out, and what is the meaning of the H in the end?
-6.38442e-86H
The entire system is too large to add here, however here is the code that printed out the particular double.
try{
newLogLikelihoodEM= hmm->learningLogLikelihood(data, Arglist::getDiffLogLikelihood(), fileNumbers, rng);
}
catch (SingularCovarianceMatrixException &scme)
{
std::cout << scme.what() << ": doing learning, so restarts for this start-point" << std::endl;
noRestarts++;
restart = true;
}
and the exception class
class SingularCovarianceMatrixException: public std::exception
{
double det;
public:
SingularCovarianceMatrixException(double det):det(det){};
virtual const char* what() const throw()
{
std::stringstream msg;
msg<< "Singular covariance matrix: determinant="<<det;
return msg.str().c_str();
}
};
And the exception is thrown by
if(*detCovarianceMatrix<1e-300)
{
throw SingularCovarianceMatrixException(*detCovarianceMatrix);
}
H is not part of the number. This is not a valid suffix for a floating point number. Something else in your code should be printing it.
H is not a valid floating point suffix, I can not find a good reference to prove this but we can show that it is not a valid conversion using this code:
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline double convertToDouble(std::string const& s,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
double x;
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion("convertToDouble(\"" + s + "\")");
return x;
}
int main()
{
double d1 = convertToDouble("-6.38442e-86") ;
std::cout << d1 << std::endl ;
d1 = convertToDouble("-6.38442e-86H");
std::cout << d1 << std::endl ;
}
Which is code I took from one of my previous answers on how to check if a string is an integer.
Related
I have a little problem with exception handling in c++. I need to convert a number to string and if this string contains letters or more than 10 characters I need to give error. Here is the exception-handling part;
while ( cin >> input )
{
try
{
convert = castInput( input );
cout << "The number entered was: " << convert;
}
catch ( NonNumber &excp )
{
cout << "INVALID INPUT: " << excp.what();
}
catch ( Overflow &excp )
{
cout << "INVALID INPUT: " << excp.what();
}
cout << "\n\nPlease enter a number (end-of-file to terminate): ";
}
I used stoi function to converting the string to int but I think I need open 2 classes. I don't know why and how becase stoi fucntion own what function already.
I personally find that a regex is no overkill for this. Checking user input with a regex will have no negative impact on performance whatsoever.
But I think that you are more interested in exception handling. You need to read many many pages of a good C++ book to understand exception handling and its use cases.
And maybe, but I do not know, you want simply to catch the standard exceptions thrown by std::stoi. These are:
std::invalid_argument
std::out_of_range
That would be easy with writing
// Standard exceptions for stoi
catch (const std::invalid_argument & e) {
std::cout << e.what() << "\n";
}
catch (const std::out_of_range & e) {
std::cout << e.what() << "\n";
}
But maybe you want to learn, how to write own exceptions. For your specific requirements. But please note that your specification, e.g. "more than 10 digits" and "no letter" are maybe not quite what you want. With a machine, where int is 32bit bit, the maximum number that can be converted is: 2147483647. Any number bigger and still having only 10 characters, will throw a std::out_of_range. On the other hand numbers like 123X would be converted by std::stoi to 123. So, maybe your requirements are not so clear.
Anyway, to show you, how you could use own exceptions, I create 2 customized exceptions classes. And to make life easy, I derived those from std::exception (recommended).
See the below example:
#include <iostream>
#include <string>
#include <algorithm>
#include <exception>
#include <cctype>
#include <vector>
#include <sstream>
class StoiException : public std::exception
{
public:
StoiException(const std::string& msg) : message(msg) {}
virtual const char* what() const noexcept override { return message.c_str(); }
protected:
void setMessage(const std::string& msg) { message = msg; }
protected:
std::string message{};
};
class NoNumber : StoiException
{
public:
NoNumber(const std::string& msg) : StoiException(msg) { setMessage(std::string("My Exception -> NoNumber: ") + msg); }
virtual const char* what() const noexcept override { return message.c_str(); }
};
class Overflow : StoiException
{
public:
Overflow(const std::string& msg) : StoiException(msg) { setMessage(std::string("My Exception -> Overflow: ") + msg); }
virtual const char* what() const noexcept override { return message.c_str(); }
};
int castInput(std::string& input) {
int result{};
// Check, if there is any letter in the input string
if (std::any_of(input.begin(), input.end(), isalpha)) {
// If so, than throw
throw NoNumber(input);
}
// Check, if string has more than 10 characters
if (input.length() > 10) {
// If so, than throw
throw Overflow(input);
}
result = std::stoi(input);
return result;
}
std::istringstream testCin{ R"(123
567
2147483647
2147483648
123X
12345678901
xyzxyzxyzxyzxyz
)" };
int main() {
std::string input{};
// Read all input
while (testCin >> input) {
try {
// Convert
int convert = castInput(input);
// This will only be shown , if there is no exception
std::cout << "\nConverted Number is: " << convert << "\n";
}
// Catch all exceptions
catch (const NoNumber & e) {
std::cout << e.what() << "\n";
}
catch (const Overflow & e) {
std::cout << e.what() << "\n";
}
// Standard exceptions for stoi
catch (const std::invalid_argument & e) {
std::cout << e.what() << "\n";
}
catch (const std::out_of_range & e) {
std::cout << e.what() << "\n";
}
}
return 0;
}
Of course you can handle the std::stoi's exception also in your custom converter function. Then only your owwn exceptions are visible.
Please see:
#include <iostream>
#include <string>
#include <algorithm>
#include <exception>
#include <cctype>
#include <vector>
#include <sstream>
class StoiException : public std::exception
{
public:
StoiException(const std::string& msg) : message(msg) {}
virtual const char* what() const noexcept override { return message.c_str(); }
protected:
void setMessage(const std::string& msg) { message = msg; }
protected:
std::string message{};
};
class NoNumber : StoiException
{
public:
NoNumber(const std::string& msg) : StoiException(msg) { setMessage(std::string("My Exception -> NoNumber: ") + msg); }
virtual const char* what() const noexcept override { return message.c_str(); }
};
class Overflow : StoiException
{
public:
Overflow(const std::string& msg) : StoiException(msg) { setMessage(std::string("My Exception -> Overflow: ") + msg); }
virtual const char* what() const noexcept override { return message.c_str(); }
};
int castInput(std::string& input) {
int result{};
// Check, if there is any letter in the input string
if (std::any_of(input.begin(), input.end(), isalpha)) {
// If so, than throw
throw NoNumber(input);
}
// Check, if string has more than 10 characters
if (input.length() > 10) {
// If so, than throw
throw Overflow(input);
}
try {
result = std::stoi(input);
}
// Standard exceptions for stoi
catch (const std::invalid_argument & e) {
throw NoNumber(input);
}
catch (const std::out_of_range & e) {
throw Overflow(input);
}
return result;
}
std::istringstream testCin{ R"(123
567
2147483647
2147483648
123X
12345678901
xyzxyzxyzxyzxyz
)" };
int main() {
std::string input{};
// Read all input
while (testCin >> input) {
try {
// Convert
int convert = castInput(input);
// This will only be shown , if there is no exception
std::cout << "\nConverted Number is: " << convert << "\n";
}
// Catch all exceptions
catch (const NoNumber & e) {
std::cout << e.what() << "\n";
}
catch (const Overflow & e) {
std::cout << e.what() << "\n";
}
}
return 0;
}
But maybe, what you really want to have, is a function, that encapsulates std::stoi and has an additional return value to show, if it worked or not.
Please note: The last solution will also convert "123X" to 123. That is the difference to the previous versions.
#include <iostream>
#include <string>
#include <algorithm>
#include <exception>
#include <cctype>
#include <vector>
#include <sstream>
std::pair<bool, int> castInput(std::string& input) {
bool ok{ false };
int result{};
try {
result = std::stoi(input);
ok = true;
}
// Catch stoi errors
catch (const std::invalid_argument & e) {}
catch (const std::out_of_range & e) {}
return {ok, result};
}
std::istringstream testCin{ R"(123
567
2147483647
2147483648
123X
12345678901
xyzxyzxyzxyzxyz
)" };
int main() {
std::string input{};
// Read all input
while (testCin >> input) {
const auto [ok, convert] = castInput(input);
if (ok)
std::cout << "Converted value: " << convert << "\n";
else
std::cout << "String '" << input << "' could not be converted\n";
}
return 0;
}
Why not use Regex ? You just create a regex that check if there is letters or more than 10 chars, depending on the return you process the conversion or throw an custom exception.
This may be the regex you are looking for: ^[0-9]{1,10}$
std::regex reg("^[0-9]{1,10}$");
if (std::regex_match(string, reg))
// Do what you want (process convert)
Here is the regex cpp reference : here
Edit: As commented, regex is overkill for this, so you could simply make some basic checks inside you castInput function and throw NonNumber if you find a character in the string, or throw Overflow if string.len > 10.
I wrote this code to check the exceptions I learned in a video, and now I tried to make the cube of an integer and if the entered number is not an integer I want the exception to be announced to the user.
#include <iostream>
float cube( float x)
{
char ch;
std::cin.get(ch);
if(ch=='.')
throw "Should be an integrer";
float cube=x*x*x;
return cube;
}
int main ()
{
float x;
std::cout<<" Enter an integrer : ";
std::cin>>x;
float cube_x=cube(x);
std::cout<<"Cube("<<x<<")="<<cube_x<<std::endl;
return 0;
}
You can use boost lexical-cast which is exactly for this purpose. It will throw an exception the conversion fails. Boost is well tested and you can safly use it to do the conversion for you.
This could look like this:
#include <boost/lexical_cast.hpp>
#include <iostream>
int cube(int x)
{
return x*x*x;
}
int main()
{
std::string x;
std::cout << " Enter an integrer : ";
std::cin >> x;
try
{
int y = boost::lexical_cast<int>(x);
int cube_x = cube(y);
std::cout << "Cube(" << x << ")=" << cube_x << std::endl;
}
catch (const boost::bad_lexical_cast &e)
{
std::cerr << e.what() << '\n';
}
return 0;
}
By the way, if your program shall only handle integers, you should also use type int and not float to handle the numbers.
Add the following to your source code:
#include <math.h> /* round, floor, ceil, trunc */
...
if (x == round(x)) {
...
}
Explanation can be found here: C++ Reference
What I want to know is, If I ask a user to input something, how will I output if the input is a Integer or String or a Float Value. I want some method to check the data type of the input in C++14.
For eg.
If the input is "Hello world"
Output should be : "The input is String"
If the input is "134"
Output should be : "The input is integer"
If the input is "133.23"
Output should be : "The input is float"
Read string.
In <string>, the standard library provides a set of functions for extracting numeric values from their character representation in a string or wstring.
Use x=stoi(s,p). Check p - if whole string was read - it is integer.
Do the same with x=stof(s,p) or x=stod(s,p), x=stold(s,p) to check for float/double/long double.
If everything fails - it is string.
The user will always input a string, what you can do is try to convert it to a float, if it succeeds then it probably is a float or an int.
If the float conversion doesnt succeed then its probably not a number.
#include <iostream>
#include <string>
#include <boost/variant.hpp>
#include <sstream>
using myvariant = boost::variant<int, float, std::string>;
struct emit : boost::static_visitor<void>
{
void operator()(int i) const {
std::cout << "It's an int: " << i << '\n';
}
void operator()(float f) const {
std::cout << "It's a float: " << f << '\n';
}
void operator()(std::string const& s) const {
std::cout << "It's a string: " << s << '\n';
}
};
auto parse(const std::string& s) -> myvariant
{
char* p = nullptr;
auto i = std::strtol(s.data(), &p, 10);
if (p == s.data() + s.size())
return int(i);
auto f = std::strtof(s.data(), &p);
if (p == s.data() + s.size())
return f;
return s;
}
void test(const std::string& s)
{
auto val = parse(s);
boost::apply_visitor(emit(), val);
}
int main()
{
test("Hello world");
test("134");
test("133.23");
}
expected output:
It's a string: Hello world
It's an int: 134
It's a float: 133.23
The input is in a string. Without additional agreements, how could you possibly know if the user intended "1" to be the string containing the character '1' or a string representation of the integer 1?
If you decide that "if it can be interpreted as an int, then it's an int. If it can be a double, then it's a double. Else it's a string", then you can just do a series of conversions until one works, or do some format checking, perhaps with a regexp.
Since all ints can be converted into doubles, and string representations of doubles can be converted into ints (perhaps with some junk left over) if you care about the difference, you probably need to check for indicators of it being a double (digits with perhaps a . in it, possibly a 'e' with +/- possibly after it. Etc. You can find regexps on the internet, depending on what you want to allow, leading +, e-notation, etc.
If it's an int, you can use regex ^\d+$, else if it's a double, [+-]?(?:0|[1-9]\d*)(?:.\d*)?(?:[eE][+-]?\d+)? else it's a string.
Here's some code that seems to work. :)
#include <iostream>
#include <string>
#include <regex>
using namespace std;
void handleDouble(double d) {
std::cout << "Double = " << d << "\n";
}
void handleInt(int i) {
std::cout << "Int = " << i << "\n";
}
void handleString(std::string const & s) {
std::cout << "String = " << s << "\n";
}
void parse(std::string const& input) {
static const std::regex doubleRegex{ R"([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)" };
static const std::regex intRegex{ R"(\d+)"};
if (std::regex_match(input, intRegex)){
istringstream inputStream(input);
int i;
inputStream >> i;
handleInt(i);
}
else if (std::regex_match(input, doubleRegex)) {
istringstream inputStream(input);
double d;
inputStream >> d;
handleDouble(d);
}
else {
handleString(input);
}
}
int main()
{
parse("+4.234e10");
parse("1");
parse("1.0");
parse("123abc");
}
output:
Double = 4.234e+10
Int = 1
Double = 1
String = 123abc
You can easily wrap string.strof for float or string.stroi for int in try-catch block:
#include <string>
bool isFloat(string str) {
try {
float floatCheck = stof(str);
return true;
}
catch (...) {
return false;
}
}
bool isInt(string str) {
try {
int intCheck = stoi(str);
return true;
}
catch (...) {
return false;
}
}
I have this class:
template<typename T> class Parser
{
public:
Parser() : count(0) {}
virtual void parse(const string&);
void get_token(void);
private:
T result;
char token;
string expression;
int count;
};
now had the class not been generic, had the result been say, a double, I would have used this method to detect numbers.
while((strchr("1234567890.",token))
{
/* add token to a "temp" string */
/* etc. etc. */
}
result = atof(temp.c_str());
But since result is generic, I can't use any method like atof and atoi etc.
What do I do?
Boost has this functionality built-in:
#include <boost/lexical_cast.hpp>
void Parser<T>::get_token() {
std::string token = ...;
result = boost::lexical_cast<T>(token);
}
Add exception handling as required.
Or, perhaps you don't want to use Boost for some reason:
void Parser<T>::get_token() {
std::string token = ...;
std::stringstream ss;
ss << token;
ss >> result;
}
Check the error state of ss as required.
More expansive answers may be found on this related question, though it discusses only int specifically.
Another generic template based Numeric To String converter. It takes ints and doubles.
#include <sstream>
#include <iostream>
#include <string>
using namespace std;
template <class T>
inline std::string Numeric_To_String (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
int main(int argc, char *argv[])
{
int i = 9;
double d = 1.2345;
string s;
cout <<"Generic Numeric_To_String( anyDatatype ) \n\n";
s = Numeric_To_String( i );
cout <<"int i to string : "<< s <<" "<< endl;
s = Numeric_To_String( d );
cout <<"double d to string : "<< s <<" "<< endl;
cout <<" \n";
return 0;
}
If you only have a hand full of types you want to parse, you can use template specialization:
template<>
void Parser<int>::parse(const string&)
{
result = atoi(string.c_str());
}
template<>
void Parser<float>::parse(const string&)
{
result = atof(string.c_str());
}
...
But this only works if you implement every convertion you need, of course.
With C++17 you can use the templated std::from_chars.
https://en.cppreference.com/w/cpp/utility/from_chars
#include <charconv>
#include <iostream>
template <typename Number>
auto stringTo(std::string_view str)
{
Number number;
std::from_chars(str.data(), str.data() + str.size(), number);
return number;
}
int main()
{
const auto str = std::string("42");
std::cout << stringTo<long>(str) << '\n';
std::cout << stringTo<double>(str) << '\n';
}
Check the return value of std::from_chars to detect errors.
const auto result = std::from_chars(...);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
{
std::cout << "string to number error" << '\n';
}
More info and examples: https://www.bfilipek.com/2018/12/fromchars.html
GCC and clang don't yet support the floating point version of std::from_chars (August 2019).
I am trying to write an if statement but cannot find the proper expression form to use. I'm thinking of writing something like this:
if ( var != type(int) )
However, I am unsure exactly how to go about doing this, and this method does not work.
Am I at least thinking along the right lines?
It sounds like you're trying to overload a function:
void foo(int i)
{
// stuff
}
void foo(float f)
{
// stuff
}
int main(void)
{
int i = 10;
float f = 1.0f;
foo(i); // calls foo(int)
foo(f); // calls foo(float)
}
If you want int-special behavior and then something else in all other cases, you can use templates:
template <typename T>
void foo(T t)
{
// T is something
}
template <>
void foo(int i)
{
// for int's only
}
int main(void)
{
int i = 10;
float f = 1.0f;
double d = 2.0;
foo(i); // calls specialized foo
foo(f); // calls generic foo
foo(d); // calls generic foo
}
According to your comment ("Task at hand is a simple program: Take two user inputted integers and add them. Restrict input to integer only. I can do it in Python and I am thinking too along those lines. if num1 != type(int): print "You did not enter an integer, please enter a integer." else: continue"), you want something like this:
#include <iostream>
int main(void)
{
int i;
std::cin >> i;
if (std::cin.fail())
{
std::cout << "Not valid!" << std::endl;
}
else
{
// ...
}
}
This will notify invalid input such as "##$", "r13", but does not catch cases such as "34fg", "12$#%", because it will read the int, and stop at "fg" and "$#%", respectively.
To check that, you will have to read in a line of input, and then try to convert that line into the type you want. (Thanks, litb). That means your question is more like this question:
#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
int i;
ss >> i;
if (ss.fail() || !(ss >> std::ws).eof())
{
std::cout << "Not valid!" << std::endl;
}
else
{
// ...
}
}
This does the following: get input, and put it into a stringstream. Then after parsing the int, stream out any remaining white space. After that, if eof is false, this means there are left-over characters; the input was invalid.
This is much easier to use wrapped in a function. In the other question, the cast was re-factored away; in this question we're using the cast, but wrapping the input along with it.
#include <iostream>
#include <sstream>
#include <string>
bool parse_int(int& i)
{
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
ss >> i;
return !(ss.fail() || !(ss >> std::ws).eof());
}
int main(void)
{
int i;
if (!parse_int(i))
{
std::cout << "Not valid!" << std::endl;
}
else
{
// ...
}
}
Or more generically:
#include <iostream>
#include <sstream>
#include <string>
template <typename T>
bool parse_type(T& t)
{
std::string input;
std::getline(std::cin, input);
std::stringstream ss(input);
ss >> t;
return !(ss.fail() || !(ss >> std::ws).eof());
}
int main(void)
{
int i;
if (!parse_type(i))
{
std::cout << "Not valid!" << std::endl;
}
else
{
// ...
}
}
This let's you parse other types with error checking.
If you're okay with exceptions, using lexical_cast (either from boost, or "faked", see the other question linked in-code [same as above link]), your code would look something like this:
#include <iostream>
#include <sstream>
#include <string>
/* Faked lexical-cast from question:
https://stackoverflow.com/questions/1243428/convert-string-to-int-with-bool-fail-in-c/
*/
template <typename T>
T lexical_cast(const std::string& s)
{
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast("Bad cast.");
}
return result;
}
template <typename T>
T parse_type(void)
{
std::string input;
std::getline(std::cin, input);
return lexical_cast<T>(input);
}
int main(void)
{
try
{
int i = parse_type<int>();
float f = parse_type<float>();
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
I don't think boost has a no-throw version of lexical cast, so we can make a true/false rather than exception version of this code by catching bad_cast's, as follows. Once again, this works with either boost or a custom lexical cast. (Anything that does a lexical cast and throws bad_cast):
#include <iostream>
#include <sstream>
#include <string>
/* Faked lexical-cast from question:
https://stackoverflow.com/questions/1243428/convert-string-to-int-with-bool-fail-in-c/
*/
template <typename T>
T lexical_cast(const std::string& s)
{
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast("Bad cast.");
}
return result;
}
template <typename T>
bool parse_type(T& t)
{
std::string input;
std::getline(std::cin, input);
try
{
t = lexical_cast<T>(input);
return true;
}
catch (const std::bad_cast& e)
{
return false;
}
}
int main(void)
{
int i;
if (!parse_type(i))
{
std::cout << "Bad cast." << std::endl;
}
}
Now it's back to a bool result, except we avoid code duplication by using existing lexical_cast functions.
You can of course choose which method you would like to use.
C++ is a statically-typed language, meaning that the type of a variable is known by the compiler at all times. In order to declare var therefore, you have to specify a type for it, which makes the if statement you posted a moot point. If you can describe a bit more the task you are trying to accomplish, perhaps there is another path to solve your problem.
That is right, more information is needed, if you are looking for an equivalent of "instanceOf" operator of Java, there isn't one, unless you use RTTI and typeid.
Do you mean that you have a floating-point value and want to know if it's an integer or not?
In that case, try this:
#include <math.h>
//...
double x = 5.0;
if(round(x) == x) {
// x has an integer value
}
Or, if the value is the result of some computation, there might be small rounding errors. Then try something like this:
double x = 4.99999999999;
if(abs(round(x) - x) < 1e-8)