Char to Int in C++? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to convert a single char into an int
Well, I'm doing a basic program, wich handles some input like:
2+2
So, I need to add 2 + 2.
I did something like:
string mys "2+2";
fir = mys[0];
sec = mys[2];
But now I want to add "fir" to "sec", so I need to convert them to Int.
I tried "int(fir)" but didn't worked.

There are mulitple ways of converting a string to an int.
Solution 1: Using Legacy C functionality
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
Solution 2: Using lexical_cast(Most Appropriate & simplest)
int x = boost::lexical_cast<int>("12345");
Solution 3: Using C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}

Alright so first a little backround on why what you attempted didn't work. In your example, fir is declared as a string. When you attempted to do int(fir), which is the same as (int)fir, you attempted a c-style cast from a string to an integer. Essentially you will get garbage because a c-style cast in c++ will run through all of the available casts and take the first one that works. At best your going to get the memory value that represents the character 2, which is dependent upon the character encoding your using (UTF-8, ascii etc...). For instance, if fir contained "2", then you might possibly get 0x32 as your integer value (assuming ascii). You should really never use c-style casts, and the only place where it's really safe to use them are conversions between numeric types.
If your given a string like the one in your example, first you should separate the string into the relevant sequences of characters (tokens) using a function like strtok. In this simple example that would be "2", "+" and "2". Once you've done that you can simple call a function such as atoi on the strings you want converted to integers.
Example:
string str = "2";
int i = atoi(str.c_str()); //value of 2
However, this will get slightly more complicated if you want to be able to handle non-integer numbers as well. In that case, your best bet is to separate on the operand (+ - / * etc), and then do a find on the numeric strings for a decimal point. If you find one you can treat it as a double and use the function atof instead of atoi, and if you don't, just stick with atoi.

Have you tried atoi or boost lexical cast?

Related

C++, how to get right double value from string?

Or which type do I need to use?
I have string and I try to convert it into double
NFR_File.ReadString(sVal); // sVal = " 0,00003"
dbl = _wtof(sVal);
and get:
3.0000000000000001e-05
And I need 0,00003, because then I should write it into the file as "0,00003" but not as 3e-05.
If the number greater then 0,0009 everything works.
displaying:
sOutput.Format(_T("%9g"),dbl);
NFP1_File.WriteString(sOutput);
I need it without trailing zeros and also reserve 9 digits (with spaces)
When you write using printf you can specify the number of significant digits you want by using the .[decimals]lf.
For example, in your case you want to print with 5 decimals, so you should use
printf("%.5f", yourNumber);
If you can use C++11
try use http://en.cppreference.com/w/cpp/string/basic_string/to_string
std::string to_string( double value );
CString::Format
Call this member function to write formatted data to a CString in the same way that sprintf formats data into a C-style character array.
It is same as c sprintf format. You may check other answer's format usage.

Converting integer to string in c++

This is the code I wrote to convert integer to string.
#include <iostream>
using namespace std;
int main()
{
string s;
int b=5;
s.push_back((char)b);
cout<<s<<endl;
}
I expected the output to be 5 but it is giving me blank space.
I know there is another way of doing it using stringstream but I want to know what is wrong in this method?
Character code for numbers are not equal to the integer the character represents in typical system.
It is granteed that character codes for decimal digits are consecutive (N3337 2.3 Character sets, Paragraph 3), so you can add '0' to convert one-digit number to character.
#include <iostream>
using namespace std;
int main()
{
string s;
int b=5;
s.push_back((char)(b + '0'));
cout<<s<<endl;
}
You are interpreting the integer 5 as a character. In ASCII encoding, 5 is the Enquiry control character as you lookup here.
The character 5 on the other hand is represented by the decimal number 53.
As others said, you can't convert an integer to a string the way you are doing it.
IMHO, the best way to do it is using the C++11 method std::to_string.
Your example would translate to:
using namespace std;
int main()
{
string s;
int b=5;
s = to_string(b);
cout<<s<<endl;
}
The problem in your code is that you are converting the integer 5 to ASCII (=> ENQ ASCII code, which is not "printable").
To convert it to ASCII properly, you have to add the ASCII code of '0' (48), so:
char ascii = b + '0';
However, to convert an integer to std::string use:
std::stringstream ss; //from <sstream>
ss << 5;
std::string s = ss.str ();
I always use this helper function in my projects:
template <typename T>
std::string toString (T arg)
{
std::stringstream ss;
ss << arg;
return ss.str ();
}
Also, you can use stringstream,
std::to_string doesn't work for me on GCC
If we were writing C++ from scratch in 2016, maybe we would make this work. However as it choose to be (mostly) backward compatible with a fairly low level language like C, 'char' is in fact just a number, that string/printing algorithms interpret as a character -but most of the language doesn't treat special. Including the cast. So by doing (char) you're only converting a 32 bit signed number (int) to a 8 bit signed number (char).
Then you interpret it as a character when you print it, since printing functions do treat it special. But the value it gets printed to is not '5'. The correspondence is conventional and completely arbitrary; the first numbers were reserved to special codes which are probably obsolete by now. As Hoffman pointed out, the bit value 5 is the code for Enquiry (whatever it means), while to print '5' the character has to contain the value 53. To print a proper space you'd need to enter 32. It has no meaning other than someone decided this was as good as anything, sometime decades ago, and the convention stuck.
If you need to know for other characters and values, what you need is an "ASCII table". Just google it, you'll find plenty.
You'll notice that numbers and letters of the same case are next to each other in the order you expect, so there is some logic to it at least. Beware, however, it's often not intuitive anyway: uppercase letters are before lowercase ones for instance, so 'A' < 'a'.
I guess you're starting to see why it's better to rely on dedicated system functions for strings!

Usage of strtol on std::string

I recently migrated from C to C++, and there's a little confusion about strings. Strings just aren't what they used to be any more, as in, not just char arrays with a terminating '\0'.
I haven't found a real answer to this question, so how far can you treat the std::string class like C-Strings?
For example: If I know there's a number somewhere in a string, let the string be ireallylike314, in C I could use strtol(string + 10, NULL, 10) to just get that number.
And, if this doesn't work, is there a way to use std::string like C-strings?
Use c_str().
strtol(string.c_str() + 10, NULL, 10);
If you want to get C-style string from std::string, then as mentioned use c_str() method. But another solution to this specific problem would be just using stol instead of strtol.
While stol doesn't (in itself) support what you want, I think I'd use it in conjunction with substr to get the required result:
std::string in = "ireallylike314";
// extract number and print it out multiplied by 2 to show we got a number
std::cout << 2 * stol(in.substr(11));
Result:
628
This has both good and bad points though. On the bad side, it creates a whole new string object to hold the digits out of the input string. On the good side, it gives a little more control over the number of digits to convert, so if (for example) you only wanted to convert the first two digits from the string (even if, as in this case, they're followed by more digits) you can do that pretty easily too:
std::cout << 2 * stol(in.substr(11, 2));
Result:
62
In quite a few cases, the degree to which this is likely to be practical for you will depend heavily upon whether your implementation includes the short string optimization. If it does, creating a (small) string is often cheap enough to make this perfectly reasonable. If it doesn't, the heap allocation to create the temporary string object as the return value from substr may be a higher price than you want to pay.
The C-like way:
long n = std::strtol( string.c_str() + offset, nullptr, 10 );
// sets ERRNO on error and returns value by saturating arithmetic.
The Java-ish way:
long n = std::stol( string.substr( offset, std::string::npos ) );
// exception (no return value) and perhaps ERRNO is set on error.
The streams way:
long n = 0;
std::istringstream( string ).ignore( offset ) >> n;
// n is unmodified on error
The locales way:
long n = 0;
std::ios_base fmt; // Use default formatting: base-10 only.
std::ios::iostate err = {};
std::num_get< char, std::string::iterator >()
.get( string.begin() + offset, string.end(), fmt, err, n );
// err is set to std::ios::failbit on error
This is maybe beyond the scope of the question but since you are migrating to C++ and you seem confused about std::string, you'll likely find the following useful.
The point of having std::string is not to use it like C-Strings (ofc you can do it, like the previous answers showed). You can take a lot more advantages of std::string capabilities. For example it is a C++ container, there are functions to get substrings, to compare strings, etc ...
String manipultions are generally a lot easier with std::string rather than C-Strings.
See for example http://www.cplusplus.com/reference/string/string/ for its capabilities.
Strings just aren't what they used to be any more, as in, not just
char arrays with a terminating '\0'.
You are wrong. In C++ strings are defined the same way. In both languages strings are defined like
A string is a contiguous sequence of characters terminated by and
including the first null character.
You mix strings with class std::string (or std::basic_string) that are not the same.
For example: If I know there's a number somewhere in a string, let the
string be ireallylike314, in C I could use strtol(string[10], NULL,
10) to just get that number
You are mistaken. The valid function call will look like
strtol( &string[11], NULL, 10)
or
strtol( string + 11, NULL, 10)
The same function you can call for an object of class std::string using member function c_str() or (starting from C++ 2011) data()
For example
std::string s( "ireallylike314" );
auto x = std::strtol( s.c_str() + 11, NULL, 10 );
or
auto x = std::strtol( s.data() + 11, NULL, 10 );

Tokenizer - Initialization with '{...}' expected for aggregate object

I'm working on creating a program that will take a fraction and reduce it to it's lowest terms. I'm using a tokenizer to parse through the string (In my case I'm reading in a string) and separate the numerator from the denominator.
I'm getting the following error, and am looking for an explanation to why it's happening. I've looked up people with similar problems, but I'm still a beginner looking for a basic explanation and suggestion for an alternative way to solve it.
RationalNum() // Default
:numerator(0), denominator(1){}
RationalNum(int num) // Whole Number
:numerator(num), denominator(1){}
RationalNum(int num, int denom) // Fractional Number
:numerator(num), denominator(denom){}
RationalNum(string s)
{
int num = 0;
char str[] = s;
}
I know the problem lies in the setting the char array to s.
Thanks for taking the time to look at this.
You are trying to initialise an array of char to a std::string, which is an object. The literal meaning of the error is that the compiler is expecting an initialisation that looks something like this :
char str[] = {'1','2','3','4'};
However, since you are planning on string manipulation anyway, you would have a much easier time just keeping the string object rather than trying to assign it to a char array.
Instead of building your parser from scratch, you can use string stream and getline. with '/' as your delimiter. You can initialise an std::stringstream with a string by passing it as an argument when constructing it. You can also use another stringstream to convert a string into a number by using the >> operator.

how to change type of value char array to int in c++? [duplicate]

This question already has answers here:
convert string to integer in c++
(3 answers)
Closed 8 years ago.
I'm new to CPP.
I'm trying to create small console app.
my qustion is, is there a way to change char array to integer...?!
for example:
char myArray[]= "12345678" to int = 12345678 ...?!
tnx
You don't "change" a type. What you want is to create an object of a certain type, using an object of the other type as input.
Since you are new to C++, you should know that using arrays for strings is not recommended. Use a real string:
std::string myString = "12345678";
Then you have two standard ways to convert the string, depending on which version of C++ you are using. For "old" C++, std::istringstream:
std::istringstream converter(myString);
int number = 0;
converter >> number;
if (!converter) {
// an error occurred, for example when the string was something like "abc" and
// could thus not be interpreted as a number
}
In "new" C++ (C++11), you can use std::stoi.
int number = std::stoi(myString);
With error handling:
try {
int number = std::stoi(myString);
} catch (std::exception const &exc) {
// an error occurred, for example when the string was something like "abc" and
// could thus not be interpreted as a number
}
Use boost::lexical_cast:
#include <boost/lexical_cast.hpp>
char myArray[] = "12345678";
auto myInteger = boost::lexical_cast<int>(myArray);
The atoi function does exactly this.
Apart from atoi() with C++11 standard compliant compiler you can use std::stoi().