Convert a no. from string to integer [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
convert string to integer in c++
Convert a no. from string to integer.
Eg: str:"1234"
convert to int a=1234;
i want the hint with proper explaination

use atoi():
int foo = atoi(str.c_str());

If you want to do this properly and test for errors in conversion, I recommend the use of boost::lexical_cast. Here is an example of usage:
#include <boost/lexical_cast>
std::string num_string("1234");
try
{
int num=boost::lexical_cast<int>(numString);
}
catch (boost::bad_lexical_cast &ex)
{
// Handle failed conversions
}
If for whatever reason you cannot use boost in your project, at least use a standard stringstream to do the conversion, in order to get some semblance of error checking.

Since you tagged it C++ you could have a look at istringstream:
bool convertStr(const char *str, unsigned int *num) {
istringstream iss(str);
return (iss >> *num);
}
Or you could even use templates:
template <class T>
bool fromString(T &t, const string &s,
ios_base& (*f)(ios_base&) = dec) {
istringstream iss(s);
return !(iss >> f >> t).fail();
}

The technique that this task is probably trying to get at is accessing each of the digits, e.g., str[0] - '0' = 1 and multiply by their place values. But atoi is much faster!

Related

How to convert a string to a signed float? [duplicate]

This question already has answers here:
std::string to float or double
(16 answers)
Closed 8 years ago.
like :
string num = "-0.25";
how can I convert it to a signed float?
C++11: std::stof(num) to convert to float; also stod for double and stold for long double.
Historically: std::strtod (or std::atof if you don't need to check for errors); or string streams.
strtod() is a good bet for C.
I have no idea if C++ has other bets.
The std::stof function should work fine.
You can use istringstream:
std::string num = "-0.25";
std::istringstream iss ( num);
float f_val = 0;
iss >> f_val;
You can convert the string to a signed float by using the function atof. Like :
float myValue = (float)atof("0.75");
Note that you should also checked if the passed value is a valid numerical value otherwise the behaviour could be unpredictable.
There is also an other solution :
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
You can use the atof function.
http://www.cplusplus.com/reference/cstdlib/atof/
For C++ you can also use std::stof
http://www.cplusplus.com/reference/string/stof/

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().

istringstream to int8_t produce unexpected result

After read this FAQ, i choose to use istringstream to convert my input string to numerical value.
My code is look like this:
<template T>
T Operand<T>::getValue(const std::string &s)
{
T _value;
std::istringstream v_ss(s);
v_ss >> _value;
return _value;
}
When T is int, short, long or float, no problem i get correct value.
But when T is int8_t, this code doesn't work.
By exemple, if my input string is "10", getValue return me a int8_t with value equals 49.
With 49 == '1' in ASCII table, i guess the >> operator just read the first char in input string and stop.
Is there a trick or something i don't understand in the FAQ ?
The problem is int8_t is implemented as char.
The implementation of the input stream is working like this:
char x;
std::string inputString = "abc";
std::istringstream is(inputString);
is >> x;
std::cout << x;
The result is 'a', because for char the input stream is read char for char.
To solve the problem, provide a specialised implementation for your template method. and reading into a int, then check the bounds and convert the value into a int8_t.

string input, how to tell if it is int?

I am writing a program that converts a parathensized expression into a mathematical one, and evaluates it. I've got the calculation bit written already.
I am using a stack for the operands, and a queue for the numbers. Adding operands to the stack isn't an issue, but I need to identify whether the input character is an integer, and if so, add it to the queue. Here's some code:
cout << "Enter the numbers and operands for the expression";
string aString;
do
{
cin >> aString
if (aString = int) // function to convert to read if int, convert to int
{
c_str(...);
atoi(...);
istack.push(int);
}
}
That's where I'm stuck now. I know I'm going to have to use c_str and atoi to convert it to an int. Am I taking the wrong approach?
Use the .fail() method of the stream.
If you need the string too, you can read to a string first, then attempt to convert the string to an integer using a stringstream object and check .fail() on the stringstream to see if the conversion could be done.
cin >> aString;
std::stringstream ss;
ss << aString;
int n;
ss >> n;
if (!ss.fail()) {
// int;
} else {
// not int;
}
I'll probably get flamed for this by the C++ purists.
However, sometimes the C++ library is just more work than the C library. I offer this
solution to C developers out there. And C++ developers who don't mind using some of the
features of the C library.
The whole check and conversion can be done in 1 line of C using the sscanf function.
int intval;
cin >> aString
if (sscanf(aString.c_str(), "%d", &intval)){
istack.push(intval);
}
sscanf returns the number of input arguments matched and assigned. So in this case, it's looking for one standard signed int value. If sscanf returns 1 then it succeeded in assigning the value. If it returns 0 then we don't have an int.
If you expect an integer, I would use boost::lexical_cast.
std::string some_string = "345";
int val = boost::lexical_cast<int>(some_string);
If it fails to cast to an integer, it will throw. The performance is pretty reasonable, and it keeps your code very clean.
I am unaware of any non-throwing version. You could use something like this, though I usually try to avoid letting exceptions control program flow.
bool cast_nothrow(const std::string &str, int &val) {
try {
val = boost::lexical_cast<int>(str);
return true;
} catch (boost::bad_lexical_cast &) {
return false;
}
}
Edit:
I would not recommend your integer validation checking for structure like you described. Good functions do one thing and one thing well.
Usually you'd want a more formal grammar parser to handle such things. My honest advice is to embed a scripting language or library in your project. It is non-trivial, so let someone else do the hard work.
If I actually tried to implement what you propose, I would probably do a stack based solution keeping the parenthesis levels at their own stack frame. The simplest thing would just be to hard code the simple operators (parenthesis, add, sub, etc) and assume that the rest of everything is a number.
Eventually you'd want everything broken down into some expression type. It might look something like this:
struct Expression {
virtual ~Expression() {}
virtual float value() const = 0;
};
struct Number : public Expression {
virtual float value() const {return val;}
float val;
};
struct AdditionOper : public Expression {
virtual float value() const {return lhs->value() + rhs->value();}
boost::shared_ptr<Expression> lhs;
boost::shared_ptr<Expression> rhs;
};
I'd start by parsing out the parenthesis, they will determine the order of your expressions. Then I'd split everything based on the numerical operands and start putting them in expressions. Then you're left with cases like 3 + 4 * 6 which would require some some care to get the order of operations right.
Good luck.
You can either run your function that converts a string representation of a number to a double and see if there's an error, or you can look at the contents of the string and see if it matches the pattern of a number and then do the conversion.
You might use boost::lexical_cast<double>() or std::stod() (C++11) where errors are reported with an exception, or istringstream extractors where the error is reported by setting the fail bit, or with C conversion functions that report errors by setting the global (thread local, rather) variable errno.
try {
istack.push_back(std::stod(aString));
} catch(std::invalid_argument &e) {
// aString is not a number
}
or
errno = 0;
char const *s = aString.c_str();
char *end;
double result = strtod(s,&end);
if(EINVAL==errno) {
// the string is not a number
} else {
istack.push_back(result);
}
An implementation of the second option might use a regex to see if the string matches the pattern you use for numbers, and if it does then running your conversion function. Here's an example of a pattern you might expect for floating point values:
std::regex pattern("[+-]?(\d*.\d+|\d+.?)([eE][+-]?\d+)?");
if(std::regex_match(aString,pattern)) {
istack.push_back(std::stod(aString));
} else {
// aString is not a number
}
Also, this probably doesn't matter to you, but most any built in method for converting a string to a number will be locale sensitive one way or another. One way to isolate yourself from this is to use a stringstream you create and imbue with the classic locale.
I guess the C++ (no boost) way would be this :
do
{
std::stringstream ss;
std::string test;
cin >> test;
ss << test;
int num;
if (ss >> num) // function to convert to read if int, convert to int
{
std::cout << "Number : " << num << "\n";
}
}while(true); // don't do this though..
Can you not use ctype.h http://www.cplusplus.com/reference/clibrary/cctype/. I have used this before and did not get into trouble.
Especially if you're doing base-10 input, I find the most blatant thing to do is read the string, then check that it only contains valid characters:
string s;
cin >> s;
if(strrspn(s.c_str(), "0123456789")==s.length()){
//int
} else{
//not int
}

How do you convert a C++ string to an int? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse a string to an int in C++?
How do you convert a C++ string to an int?
Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).
Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.
#include <sstream>
// st is input string
int result;
stringstream(st) >> result;
Use the C++ streams.
std::string plop("123");
std::stringstream str(plop);
int x;
str >> x;
/* Lets not forget to error checking */
if (!str)
{
// The conversion failed.
// Need to do something here.
// Maybe throw an exception
}
PS. This basic principle is how the boost library lexical_cast<> works.
My favorite method is the boost lexical_cast<>
#include <boost/lexical_cast.hpp>
int x = boost::lexical_cast<int>("123");
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).
I have used something like the following in C++ code before:
#include <sstream>
int main()
{
char* str = "1234";
std::stringstream s_str( str );
int i;
s_str >> i;
}
C++ FAQ Lite
[39.2] How do I convert a std::string to a number?
https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num
Let me add my vote for boost::lexical_cast
#include <boost/lexical_cast.hpp>
int val = boost::lexical_cast<int>(strval) ;
It throws bad_lexical_cast on error.
Use atoi
Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.
Am I just missing the point here?
in "stdapi.h"
StrToInt
This function tells you the result, and how many characters participated in the conversion.