Hello
I know it was asked many times but I hadn't found answer to my specific question.
I want to convert only string that contains only decimal numbers:
For example 256 is OK but 256a is not.
Could it be done without checking the string?
Thanks
The simplest way that makes error checking optional that I can think of is this:
char *endptr;
int x = strtol(str, &endptr, 0);
int error = (*endptr != '\0');
In C++ way, use stringstream:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream sstr;
int a = -1;
sstr << 256 << 'a';
sstr >> a;
if (sstr.failbit)
{
cout << "Either no character was extracted, or the character can't represent a proper value." << endl;
}
if (sstr.badbit)
{
cout << "Error on stream.\n";
}
cout << "Extracted number " << a << endl;
return 0;
}
An other way using c++ style : We check the number of digits to know if the string was valid or not :
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
int main(int argc,char* argv[]) {
std::string a("256");
std::istringstream buffer(a);
int number;
buffer >> number; // OK conversion is done !
// Let's now check if the string was valid !
// Quick way to compute number of digits
size_t num_of_digits = (size_t)floor( log10( abs( number ) ) ) + 1;
if (num_of_digits!=a.length()) {
std::cout << "Not a valid string !" << std::endl;
}
else {
std::cout << "Valid conversion to " << number << std::endl;
}
}
Related
Im trying to make a number that is positive (already converted into a string) look like "+number" instead of "number" but i can't define it in an if
#include <iostream>
#include <string>
int main()
{
std::string x3s;
int number = 145;
if (number >= 0)
{
x3s = "+" + number;
}
std::cout << x3s << std::endl;
}
Firstly, there is an I/O manipulator std::showpos.
#include <iostream>
int main()
{
int number = 145;
std::cout << std::showpos << number << std::endl;
}
Secondly, you are using the verb "define" incorrectly.
You can use x3s = std::string("+") + std::to_string(number);
lexical_cast throws an exception in the following case. Is there a way to use lexical_cast and convert the string to integer.
#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
int main()
{
std::string src = "124is";
int iNumber = boost::lexical_cast<int>(src);
std::cout << "After conversion " << iNumber << std::endl;
}
I understand, I can use atoi instead of boost::lexical_cast.
If I'm understanding your requirements correctly it seems as though removing the non-numeric elements from the string first before the lexical_cast will solve your problem. The approach I outline here makes use of the isdigit function which will return true if the given char is a digit from 0 to 9.
#include <iostream>
#include "boost/lexical_cast.hpp"
#include <string>
#include <algorithm>
#include <cctype> //for isdigit
struct is_not_digit{
bool operator()(char a) { return !isdigit(a); }
};
int main()
{
std::string src = "124is";
src.erase(std::remove_if(src.begin(),src.end(),is_not_digit()),src.end());
int iNumber = boost::lexical_cast<int>(src);
std::cout << "After conversion " << iNumber << std::endl;
}
The boost/lexical_cast uses stringstream to convert from string to other types,so you must make sure the string can be converted completely! or, it will throw the bad_lexical_cast exception,This is an example:
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#define ERROR_LEXICAL_CAST 1
int main()
{
using boost::lexical_cast;
int a = 0;
double b = 0.0;
std::string s = "";
int e = 0;
try
{
// ----- string --> int
a = lexical_cast<int>("123");//good
b = lexical_cast<double>("123.12");//good
// -----double to string good
s = lexical_cast<std::string>("123456.7");
// ----- bad
e = lexical_cast<int>("abc");
}
catch(boost::bad_lexical_cast& e)
{
// bad lexical cast: source type value could not be interpreted as target
std::cout << e.what() << std::endl;
return ERROR_LEXICAL_CAST;
}
std::cout << a << std::endl; // cout:123
std::cout << b << std::endl; //cout:123.12
std::cout << s << std::endl; //cout:123456.7
return 0;
}
The following code converts an std::string to int and the problem lies with the fact that it cannot discern from a true integer or just a random string. Is there a systematic method for dealing with such a problem?
#include <cstring>
#include <iostream>
#include <sstream>
int main()
{
std::string str = "H";
int int_value;
std::istringstream ss(str);
ss >> int_value;
std::cout<<int_value<<std::endl;
return 0;
}
EDIT: This is the solution that I liked because it is very minimal and elegant! It doesn't work for negative numbers but I only needed positive ones anyways.
#include <cstring>
#include <iostream>
#include <sstream>
int main()
{
std::string str = "2147483647";
int int_value;
std::istringstream ss(str);
if (ss >> int_value)
std::cout << "Hooray!" << std::endl;
std::cout<<int_value<<std::endl;
str = "-2147483648";
std::istringstream negative_ss(str);
if (ss >> int_value)
std::cout << "Hooray!" << std::endl;
std::cout<<int_value<<std::endl;
return 0;
}
You may try to use Boost lexical_cast, it will throw an exception if the cast failed.
int number;
try
{
number = boost::lexical_cast<int>(str);
}
catch(boost::bad_lexical_cast& e)
{
std::cout << str << "isn't an integer number" << std::endl;
}
EDIT
Accorinding to #chris, You may also try to use std::stoi since C++11. It will throw std::invalid_argument exception if no conversion could be performed. You may find more information here: std::stoi
WhozCraig's approach is much nicer and I wanted to expand on it using the approach that the C++ FAQ uses which is as follows:
#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 int convertToInt(std::string const& s,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
int x;
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion("convertToInt(\"" + s + "\")");
return x;
}
int main()
{
std::cout << convertToInt( "100" ) << std::endl ;
std::cout << convertToInt( "-100" ) << std::endl ;
std::cout << convertToInt( " -100" ) << std::endl ;
std::cout << convertToInt( " -100 ", false ) << std::endl ;
// The next two will fail
std::cout << convertToInt( " -100 ", true ) << std::endl ;
std::cout << convertToInt( "H" ) << std::endl ;
}
This is robust and will know if the conversion fails, you also can optionally choose to fail on left over characters.
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char str[]="1776ad";
int year;
if (isdigit(str[0]))
{
year = atoi (str);
printf ("The year that followed %d was %d.\n",year,year+1);
}
return 0;
}
I want to know how can I make the string I converted from DWORD to onstringstream and then to AnsiString.
But that doesn't really matter, the conversion could be from int to string, I just want to know how I can make every string converted to ALWAYS show 6 digits, like if my number is 57, in the string it will be 000057.
Thanks!
Use io manipulators setfill and setw:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
int main()
{
std::ostringstream s;
s << std::setfill('0') << std::setw(6) << 154;
std::cout << s.str() << "\n";
return 0;
}
So, the question about formatted output?
you can use iostream::width and `iostream::fill':
// field width
#include <iostream>
using namespace std;
int main () {
cout << 100 << endl;
cout.width(6);
cout.fill('0');
cout << 100 << endl;
return 0;
}
I would like to know what is the easiest way to convert an int to C++ style string and from C++ style string to int.
edit
Thank you very much. When converting form string to int what happens if I pass a char string ? (ex: "abce").
Thanks & Regards,
Mousey
Probably the easiest is to use operator<< and operator>> with a stringstream (you can initialize a stringstream from a string, and use the stream's .str() member to retrieve a string after writing to it.
Boost has a lexical_cast that makes this particularly easy (though hardly a paragon of efficiency). Normal use would be something like int x = lexical_cast<int>(your_string);
You can change "%x" specifier to "%d" or any other format supported by sprintf. Ensure to appropriately adjust the buffer size 'buf'
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
EDIT 2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
This is to convert string to number.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
Like wise, the following is to convert number to string.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
Use atoi to convert a string to an int. Use a stringstream to convert the other way.