Convert String to Int With Bool/Fail in C++

Convert string to int with bool/fail in C++

Use boost::lexical_cast. If the cast cannot be done, it will throw an exception.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

int main(void)
{
std::string s;
std::cin >> s;

try
{
int i = boost::lexical_cast<int>(s);

/* ... */
}
catch(...)
{
/* ... */
}
}

Without boost:

#include <iostream>
#include <sstream>
#include <string>

int main(void)
{
std::string s;
std::cin >> s;

try
{
std::stringstream ss(s);

int i;
if ((ss >> i).fail() || !(ss >> std::ws).eof())
{
throw std::bad_cast();
}

/* ... */
}
catch(...)
{
/* ... */
}
}

Faking boost:

#include <iostream>
#include <sstream>
#include <string>

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();
}

return result;
}

int main(void)
{
std::string s;
std::cin >> s;

try
{
int i = lexical_cast<int>(s);

/* ... */
}
catch(...)
{
/* ... */
}
}

If you want no-throw versions of these functions, you'll have to catch the appropriate exceptions (I don't think boost::lexical_cast provides a no-throw version), something like this:

#include <iostream>
#include <sstream>
#include <string>

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();
}

return result;
}

template <typename T>
bool lexical_cast(const std::string& s, T& t)
{
try
{
// code-reuse! you could wrap
// boost::lexical_cast up like
// this as well
t = lexical_cast<T>(s);

return true;
}
catch (const std::bad_cast& e)
{
return false;
}
}

int main(void)
{
std::string s;
std::cin >> s;

int i;
if (!lexical_cast(s, i))
{
std::cout << "Bad cast." << std::endl;
}
}

I can't convert string to int

        string textBoxString = textBox1.Text.ToString();
int textBoxInt = int.Parse(textBoxString);
int test = textBoxInt + 1;
string testText = test.ToString();
MessageBox.Show(testText);

converting the variable into string first then converting into int solved this problem

How to convert a string to integer in C?

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be
represented, the behavior is undefined
.

C++: avoid automatic conversion of string to bool in overloads

You could add an template overload that takes a reference to array of char of size N where N is a template parameter, and/or one that accepts a const char*.

template <std::size_t N>
static void printValue(sts::ostringstream& out, const char (&str)[N])
{
out << str;
}

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
bool myBool = bool.Parse(sample);

// Or

bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

string sample = "false";
Boolean myBool;

if (Boolean.TryParse(sample , out myBool))
{
// Do Something
}

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Hope you understand :)

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)



1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”

2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

How to parse a string to an int in C++?

In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.

int myNr = std::stoi(myString);

It will throw an exception on conversion error.

Even these new functions still have the same issue as noted by Dan: they will happily convert the string "11x" to integer "11".

See more: http://en.cppreference.com/w/cpp/string/basic_string/stol

How to take care of this error: invalid conversion from 'bool (*)(int)' to 'int'?

You pass an entire Dummy to the predicate function when you call pred((curr -> data). pred, coming from the line dummy1 = dummy1.filter(teeth_list, &func);, is a function expecting an int, which it doesn't get.

There are a couple of potential fixes.

  1. Use a function that expects a Dummy (and extracts the teeth itself ;-) ).
  2. Pass the number of teeth (which are currently inaccessible), not the entire Dummy.
  3. Providing a conversion operator to int in Dummy (presumably returning the number of teeth) should work as well.

The conversion operator approach seemed to work for me. I inserted

    operator int() { return num_of_teeth; }

into the Dummy class in the public section.

Whether that is good style is debatable. It may be unexpected that a Dummy is also an int. There is perhaps also an argument that the predicate function should work on the entire node data, but that is debatable: A general, reusable function that can handle everything int-oid has its merits as well. Since C++11 you can mitigate the unexpectedness of a conversion to int by making it explicit: It is still possible but requires a static cast.

As for the rest of the code:

  • Define a proper assignment for the list: head = t.head;— a shallow copy, sharing all nodes — leads to double deletes on each node when the lists go out of scope
  • Do not mix malloc and delete
  • Do not use naked pointers in the first place, use smart pointers
  • Check your insert function, the logic seems overly complicated and may be buggy
  • The Node constructor should also null next
  • You'll likely need const iterators.

Make sure to write extensive tests for such a container class with wild inserts and deletes, at the beginning, the end etc. Make sure to cover all edge cases with empty lists. Containers are hard to get perfectly correct without rigorous tests.

Converting bool to text in C++

How about using the C++ language itself?

bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;

UPDATE:

If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha and std::noboolalpha which shows you the console output and explains more about the API.

Additionally using std::boolalpha will modify the global state of std::cout, you may want to restore the original behavior go here for more info on restoring the state of std::cout.

How can I convert a std::string to int?

In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

atoi( str.c_str() )

you can use

std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers:
long stol(string), float stof(string), double stod(string),...
see http://en.cppreference.com/w/cpp/string/basic_string/stol



Related Topics



Leave a reply



Submit