Convert octal string to decimal string in C++ - c++

What is the easiest way to convert string holding octal number into string holding decimal representation of the same number?
I could convert it into int value using strtol, then convert into string again using stringstream:
string oct_number("203");
// converts into integer
int value = strtol(oct_number.c_str(), NULL, 8);
// converts int to decimal string
stringstream ss;
ss << value;
string dec_number = ss.str();
But: is there any quicker way to do it?
I have a rather poor understanding of the stringstream class, am I missing something?

std::string result;
Try
{
result = std::to_string( std::stoi( oct_number, 0, 8 ) );
}
catch ( ... )
{
//...
}

In c++11 you can use string dec_number = to_string (value);.
Also you can use sprintf but you will need some buffer:
char buf[64];
sprintf(buf,"%d",value);
string dec_number = buf;

Related

Multiplying string by a factor in C++

Is there a simple way to create a string with a repeating sequence by multiplying the string by a factor. For example in python I can do 3*'ab' to get ababab.
Can I do something like this in C++? The string constructor will only take a char.
I am looking for a way to string together a sequence of strings depending on a loop counter.
You can always overload *
Something like this :
std::string operator*(std::string const &str, size_t times)
{
std::string res;
res.reserve(times * str.size());
for (size_t i=0; i<times; ++i)
res += str;
return res;
}
std::string s="ab";
std::cout<<s*3<<std::endl;
Edit for "I was hoping I didn't need to go into another for loop. – Dochevsky"
You can use std::fill_n and std::stringstream
#include<algorithm>
#include<sstream>
//...
std::stringstream ss;
std::fill_n( std::ostream_iterator< const char* >( ss ),
3, "ab" ); //Replace ss with std::cout, to output on standard output
std::string str =ss.str();
std::cout<<str;

Alternate way to get the Byte Length of a Hex string

I have created a function to count the byte length of an incoming hex string, then convert that length into hexidecimal. It first assigns the Byte Length of the incoming string to an int, then I convert the int to a string. After assigning the byte length of my incoming string to an int, I check to see if it is more than 255, if it is, I insert a zero so that I have 2 bytes returned, instead of 3-bits.
I do the follwing:
1) Takes in the Hex string and divides the number by 2.
static int ByteLen(std::string sHexStr)
{
return (sHexStr.length() / 2);
}
2) Takes in Hex string, then converts to a Hex format string with itoa()
static std::string ByteLenStr(std::string sHexStr)
{
//Assign the length to an int
int iLen = ByteLen(sHexStr);
std::string sTemp = "";
std::string sZero = "0";
std::string sLen = "";
char buffer [1000];
if (iLen > 255)
{
//returns the number passed converted to hex base-16
//if it is over 255 then it will insert a 0 infront
//so to have 2 bytes instead of 3-bits
sTemp = itoa (iLen,buffer,16);
sLen = sTemp.insert(0,sZero);
return sLen;
}
else{
return itoa (iLen,buffer,16);
}
}
I convert the length to hexidecimal. This seems to work fine, however I am looking for maybe a more simpler way to format the text like I would in C# with the ToString("X2") method. Is this it for C++ or does my method work well enough?
Here is how I would do it in C#:
public static int ByteLen(string sHexStr)
{
return (sHexStr.Length / 2);
}
public static string ByteLenStr(string sHexStr)
{
int iLen = ByteLen(sHexStr);
if (iLen > 255)
return iLen.ToString("X4");
else
return iLen.ToString("X2");
}
My logic may be off a bit in C++, but the C# method is good enough for me in what I want to do.
Thank you for your time.
static std::string ByteLenStr(std::string& sHexStr)
{
int iLen = ByteLen(sHexStr);
char buffer[16];
snprintf(buffer, sizeof(buffer), (iLen > 255) ? "%04x" : "%02x", iLen);
return buffer;
}
snprintf formats text in a buffer using a format string and a variable list of arguments. We are using the %x format code to convert a int argument into a hex string. In this instance, we have two format strings to choose from:
When iLen > 255, we want the number to be four digits long. %04x means format as a hex string, with zero-padding at the beginning up to four places.
Otherwise, we want the number to be two digits long. %02x means format as a hex string, with zero-padding up to two places.
We use the ternary operator to select which format string we use. Finally, iLen is passed as the single argument which will be used to provide the value that is formatted by the function.
For a purely C++ solutuon that does not use any C functions, try using a std::stringstream to help you with formatting:
static std::string ByteLenStr(std::string sHexStr)
{
//Assign the length to an int
int iLen = ByteLen(sHexStr);
//return the number converted to hex base-16
//if it is over 255 then insert a 0 in front
//so to have 2 bytes instead of 3-bits
std::stringstream ss;
ss.fill('0');
ss.width((iLen > 255) ? 4 : 2);
ss << std::right << std::hex << iLen;
return ss.str();
}

Read number from file, increment and write back

I want to read a long number from file then increment it and write it back to file.
I am struggling with the convertion from string to long and back again.
I tried:
double id = atof("12345678901"); //using atof because numbers are too big for atio()
id++;
ostringstream strs;
strs << static_cast<long>((static_cast<double>(threadId)));
string output = strcpy_s(config->m_threadId, 20, strs.str().c_str());
But that converts the input to a negative or wrong number.
atoi is for normal integers. There's also atol and atoll (_atoi64 in windows):
//long long id = atoll( "12345678901" );
long long id = _atoi64("12345678901"); // for Visual Studio 2010
id++;
// write back to file here
As suggested by one commenter, use strtoll instead of the ato* functions:
char * data = "12345678901";
long long id = strtoull( data, NULL, 10 );
id++;
Since you're using C++ here, you should just pull it straight from the fstreams:
long long id;
{
std::ifstream in( "numberfile.txt" );
in >> id;
}
id++;
{
std::ofstream out( "numberfile.txt" );
out << id;
}
To go from a C string (char array), use this:
long id = atol("12345678901");
Now you can increment the number. Then, to go from a long to a C++ std::string, use this:
std::ostringstream oss;
oss << id;
std::string idAsStr = oss.str();
Now you can write the string back to the file.
Do you have access to Boost.Lexical_Cast? You could simply do the conversion like this:
double id = boost::lexical_cast<double>("some string");
++id
std::string id_string = boost::lexical_cast<std::string>(id);
and use whatever file transfer you currently have.

atoi with ints and doubles

Can I use atoi to convert a text input to a dialog box to a double?
I need to do a calculation on several double values that have been input using a dialog box. I only know of 'atoi' but is this for integers only?
Similar to atoi() there is double atof ( const char * str ) that you can use
Reference
Assuming Boost is an option, Boost.lexical_cast is a popular approach for converting to and from string representations of numerical values, e.g.:
char const s[] = "1.2345";
try
{
double d = boost::lexical_cast<double>(s);
...
}
catch (boost::bad_lexical_cast &)
{
...
}
Check the atoi, atol, strtol family :
http://www.fiveanddime.net/man-pages/strtol.3.html
http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html
If you are really using C++ (not just C) then you can parse text into floats using stl's std::istringstream.
You can use std::stringstream as:
std::stringstream ss(text);
double value;
if ( !( ss >> value ) )
{
std::cout << "error : text is not double" << std::endl;
}
Both atoi and atof are more or less broken; there's no way to do any error checking. In most cases, the simplest solution would be to use strtod:
char* endPtr;
errno = 0;
value = strtod( input, &endPtr );
if ( errno != 0 || *skipSpaces( endPtr ) != '\0' )
// Illegal input, conversion failed.
(I'm generally a fan of istringstream, but in this case, it seems overkill.)

how to convert ascii to unsigned int

Is there a method that converts string to unsigned int?
_ultoa exists but couldn't find the vise verse version...
std::strtoul() is the one. And then again there are the old ones like atoi().
Boost provides lexical_cast.
#include <boost/lexical_cast.hpp>
[...]
unsigned int x = boost::lexical_cast<unsigned int>(strVal);
Alternatively, you can use a stringstream (which is basically what lexical_cast does under the covers):
#include <sstream>
[...]
std::stringstream s(strVal);
unsigned int x;
s >> x;
sscanf will do what you want.
char* myString = "123"; // Declare a string (c-style)
unsigned int myNumber; // a number, where the answer will go.
sscanf(myString, "%u", &myNumber); // Parse the String into the Number
printf("The number I got was %u\n", myNumber); // Show the number, hopefully 123
It works if you go via _atoi64
unsigned long l = _atoi64(str);
How about int atoi ( const char * str ) ?
string s("123");
unsigned u = (unsigned)atoi(s.c_str());