Getting the char integer value from a std::string & std::wstring
the *toi family of functions converts a string representation to integer representation, that is, "10" becomes 10. What you actually want to do is no conversion at all. Change it to:
printf("TEST a: %d \n", _T('a'));
printf("TEST A: %d \n", _T('A'));
printf("TEST b: %d \n", _T('b'));
As for unicode, the underlying representation depends on the encoding ( for example UTF-8, which is very popular, maps the LSB with the ASCII table ).
Ruby Nil and Zero
NilClass
defines #to_i
for the same reason it defines a #to_a
that returns [].
It's giving you something of the right type but an empty sort of value.
This is actually quite useful. For example:
<%= big.long.expr.nil? ? "" : big.long.expr %>
becomes:
<%= big.long.expr %>
Much nicer! (Erb is calling #to_s which, for nil, is "".) And:
if how.now.brown.cow && how.now.brown.cow[0]
how.now.brown.cow[0]
else
0
end
becomes:
how.now.brown.cow.to_a[0].to_i
The short conversions exist when only a representation is needed. The long conversions are the ones that the Ruby core methods call and they require something very close. Use them if you want a type check.
That is:
thing.to_int # only works when almost Integer already. NilClass throws NoMethodError
thing.to_i # this works for anything that cares to define a conversion
What is the difference between std::atoi() and std::stoi?
1). Are there any other differences between the two?
I find std::atoi()
a horrible function: It returns zero on error. If you consider zero as a valid input, then you cannot tell whether there was an error during the conversion or the input was zero. That's just bad. See for example How do I tell if the c function atoi failed or if it was a string of zeros?
On the other hand, the corresponding C++ function will throw an exception on error. You can properly distinguish errors from zero as input.
2). Efficiency and performance wise which one is better?
If you don't care about correctness or you know for sure that you won't have zero as input or you consider that an error anyway, then, perhaps the C functions might be faster (probably due to the lack of exception handling). It depends on your compiler, your standard library implementation, your hardware, your input, etc. The best way is to measure it. However, I suspect that the difference, if any, is negligible.
If you need a fast (but ugly C-style) implementation, the most upvoted answer to the How to parse a string to an int in C++? question seems reasonable. However, I would not go with that implementation unless absolutely necessary (mainly because of having to mess with char*
and \0
termination).
3). Which is safer to use?
See the first point.
In addition to that, if you need to work with char*
and to watch out for \0
termination, you are more likely to make mistakes. std::string
is much easier and safer to work with because it will take care of all these stuff.
+= operator for uint16_t promotes the assigned value to int and won't compile
The reason for the implicit conversion is due to the equivalency of the +=
operator with =
and +
.
From section 6.5.16.2 of the C standard:
3 A compound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue
E1 is evaluated only once, and with respect to an
indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation
So this:
i += ((uint16_t)3);
Is equivalent to:
i = i + ((uint16_t)3);
In this expression, the operands of the +
operator are promoted to int
, and that int
is assigned back to a uint16_t
.
Section 6.3.1.1 details the reason for this:
2 The following may be used in an expression wherever an
int
orunsigned int
may be used:
- An object or expression with an integer type (other than
int
orunsigned int
) whose integer conversion rank is less than or equal to
the rank ofint
andunsigned int
.- A bit-field of type
_Bool
,int
,signed int
, orunsigned int
.
If an
int
can represent all values of the original type (as restricted
by the width, for a bit-field), the value is converted to anint
;
otherwise, it is converted to anunsigned int
. These are called the
integer promotions. All other types are unchanged by the integer
promotions.
Because a uint16_t
(a.k.a. an unsigned short int
) has lower rank than int
, the values are promoted when used as operands to +
.
You can get around this by breaking up the +=
operator and casting the right hand side. Also, because of the promotion, the cast on the value 3 has no effect so that can be removed:
i = (uint16_t)(i + 3);
Note however that this operation is subject to overflow, which is one of the reasons a warning is given when there is no cast. For example, if i
has value 65535, then i + 3
has type int
and value 65538. When the result is cast back to uint16_t
, the value 65536 is subtracted from this value yielding the value 2, which then gets assigned back to i
.
This behavior is well defined in this case because the destination type is unsigned. If the destination type were signed, the result would be implementation defined.
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
Stream Sorted, Reversed Absolute Value based on , implementing Comparator or ToIntFunction, Java 8
Check this Question:
someList
.sorted((a, b) ->
Integer.valueOf(b.getValue() < 0 ? -b.getValue() : b.getValue())
.compareTo(a.getValue() < 0 ? -a.getValue() : a.getValue())
)
According to implementation of Math.abs(x)
is the same code that you are requiring.
someList
.sorted((a, b) ->
Integer.valueOf(Math.abs(b.getValue()))
.compareTo(Math.abs(a.getValue()))
)
Alternatively
someList
.sorted(Comparator.<SomeClass>comparingInt(s -> Math.abs(s.getValue())).reversed())
Ruby .to_i does not return the complete integer as expected
You can achieve it by doing this :
"980,323,344.00".delete(',').to_i
The reason your method call to to_i
does not return as expected is explained here, and to quote, the method :
Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored.
Extraneous characters in your case would be the comma character that ends at 980
, the reason why you see 980
being returned
Related Topics
How Does Ruby's Sort_By {Rand} Work
What Is the Best Practice When It Comes to Testing "Infinite Loops"
Ruby Gets/Puts Only for Strings
How to Fire Raw Mongodb Queries Directly in Ruby
Rails Active Admin CSS Conflicting with Twitter Bootstrap CSS
Throw Exception When Re-Assigning a Constant in Ruby
Remove from the Array Elements That Are Repeated
Rubygems, Bundler and Rvm Confusion
Setting Path for Whenever in Cron So It Can Find Ruby
Nested Forms in Rails - Accessing Attribute in Has_Many Relation
Ruby Block to String Instead of Executing
Parse Email Addresses for "From" and "To" Fields in Ruby
How to Use Controller Specific Stylesheets in Rails 3.2.1
Converting a Hash into a Nested Hash
Ruby Variable (Array) Assignment Misunderstanding (With Push Method)