Dividing pointer char array to other arrays - c++

When I printed it I got error like this 17:1733╠╠╠╠╠╠╠╠17:╠╠.
I couldn't figure it out. I would appreciate if you solve and give me a better approach? Thanks for your help.
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char* time = "173324";
char holdh[3];
char holdM[3];
char holds[3];
holdh[2] = '\0';
holdM[2] = '\0';
holds[2] = '\0';
int t;
for (t = 0; t < 6;t++)
{
if (t < 2)
holdh[t] = *(time + t);
else if (2 <= t < 4) {
t = t - 2;
holdM[t] = *(time + t);
t = t + 2;
}
else if (4 <= t < 6)
{
t = t - 4;
holds[t] = *(time + t);
t = t + 4;
}
}
string h(holdh);
string M(holdM);
string s(holds);
string datex = h + ":" + M + ":" + s;
cout << datex;
return 0;
}
It might be overflow of memory but I tried to prevent that by assigning null values. So if I have a problem in there too please inform. Thanks again.

The expression 2 <= t < 4 is equal to (2 <= t) < 4. That is, check if the result of 2 <= t (which is a bool true or false) is smaller than 4, which is will always be as boolean results are either 0 (for false) or 1 (for true).
If you want to compare a range, you need to to e.g. 2 <= t && t < 4.
More generally, I advice you to not use a loop for this. Do the assignments directly instead:
// Create three arrays and initialize all elements to zero
char holdh[3] = {};
char holdM[3] = {};
char holds[3] = {};
holdh[0] = time[0];
holdh[1] = time[1];
holdM[0] = time[2];
holdM[1] = time[3];
holds[0] = time[4];
holds[1] = time[5];
Much simpler and show your intent much more clearly.
And you don't even need the temporary holdX variables, as you can just get the sub-strings from time and initialize h, M and s directly:
const char* time = "173324";
std::string h(time + 0, time + 2);
std::string M(time + 2, time + 4);
std::string s(time + 4, time + 6);
And do you really need the also temporary h, M and s variables?
std::cout << std::string(time + 0, time + 2) << ':'
<< std::string(time + 2, time + 4) << ':'
<< std::string(time + 4, time + 6) << '\n';
And do you really need freshly allocated strings?
std::cout << std::string_view(time + 0, 2) << ':'
<< std::string_view(time + 2, 2) << ':'
<< std::string_view(time + 4, 2) << '\n';

Your code is an textbook example of bad use of if() statement inside of loop.
What happens that you repeat all same checks in every iterations, while you actually know where iterations must stop.
And you made assumption that if() checks every comparison inside its expression. It doesn't. It evaluates expression and checks if result is equivalent of non-zero value or boolean true. Thus if(4 <= t < 6) is a bug. It's an equivalent of if( (4 <= t) < 6 ). (a <= t) < b is always true, if b is grater than 1.
SImplest conversion of your code would be:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <string>
using std::string;
using std::cout;
int main()
{
const char* time = "173324";
// note, that making it non-const is a not standard compliant
char hold[3][3] = {}; // zero initialization
for (int t = 0; t < 6;t++)
{
hold[t / 2][t % 2] = time[t];
}
string h(hold[0]);
string M(hold[1]);
string s(hold[2]);
string datex = h + ":" + M + ":" + s;
cout << datex;
return 0;
}
Or maybe even so:
string hold[3];
for (int t = 0; t < 6;t++)
{
hold[t / 2] += time[t];
}
string datex = hold[0] + ":" + hold[1] + ":" + hold[2];
But better you should avoid making loops at all, provided string got constructor that receives iterators for beginning and end of source.
std::string h(time + 0, time + 2);

Related

Combining elements of an integer array into a single integer variable

I am writing a simple C++ program that should combine all elements of an integer array to form one number. Eg. {4,5,6} --> should be 456. But my output is one less than the original number. i.e instead of 456, I am getting 455. Sometimes my program works fine and sometimes not. Can someone please explain to me what is causing this unpredictible behaviour? Thank You!!
Please take a look at my code:
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
int main()
{
int A[5] = {4,5,6,7,8};
int lengthA = 5;
int num = 0;
for(int x = 0; x < lengthA; x++)
{
num = A[x]*pow(10,lengthA-1-x) + num;
}
printf("%d\n", num ); // My O/P is 45677
}
As mentioned by Bob__, pow is a function for doubles and other floating-point types. For this specific algorithm, instead, we can do this:
int A[5] = {4,5,6,7,8};
int lengthA = 5;
int num = 0;
for(int x = 0; x < lengthA; x++)
{
num = num*10 + A[x];
}
At each step, this multiplies the previous number by 10, and makes the digit correct at that place.
E.g.
Step 1: num = 0*10 + 4 == 4
Step 2: num = 4 * 10 + 5 == 40 + 5 == 45
Step 3: num = 45 * 10 + 6 == 450 + 6 == 456
Step 4: num = 456 * 10 + 7 == 4560 + 7 == 4567
Step 5: num == 4567 * 10 + 8 == 45670 + 8 == 45678
From this simple problem you can already learn quite a bit to improve your C++ code.
Example :
// #include <bits/stdc++.h> // NO : https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h
// using namespace std // NO : https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
#include <iostream> // include only what you need for std::cout
int main()
{
int values[]{ 4,5,6,7,8 }; // no need for an =
int num{ 0 };
// prefer range based for loops
// they will not run out of bounds
// https://en.cppreference.com/w/cpp/language/range-for
for (const int value : values)
{
num *= 10;
num += value;
}
// avoid printf, use std::cout with C++20 std::format for formatting
// https://stackoverflow.com/questions/64042652/is-printf-unsafe-to-use-in-c
// https://en.cppreference.com/w/cpp/utility/format/format
std::cout << "num = " << num << "\n";
return 0;
}
Here is another way for this problem. You can use string to convert this numbers as you need.
With this loop, we convert each number to string and pase it to end of the num string. At the end, you have the number as you need as string. If you need that number as integer, you can conver it back at the end of the loop. To conver string to int you can check this :Converting String to Numbers
#include <iostream> //include to use cout
#include <string> // include to use string
using namespace std;
int main() {
int A[5] = {4,5,6,7,8}; // input array
int lengthA = sizeof(A) / sizeof(A[0]); // size of array
std::string num = "";
for(int i=0; i<lengthA; i++){
num += std::to_string(A[i]);
}
std::cout << "Number : " << num;
}
In addition to jh316's solution;
#include <iostream>
using namespace std;
int A[] = {4,5,6,7,8};
int num = 0;
int main()
{
for(int i: A){
num = num * 10 + i;
}
cout << num;
}
Description of the code:
Initial state of the variable: num = 0
For each iteration the num variable is:
1. num = 0 * 10 + 4 = 4
2. num = 4 * 10 + 5 = 45
3. num = 45 * 10 + 6 = 456
4. num = 456 * 10 + 7 = 4567
5. num = 4567 * 10 + 8 = 45678
Here when you call pow;
pow(10,lengthA-1-x)
your code is probably calling the following overload of std::pow:
double pow ( double base, int iexp );
And as can be seen, it returns a floating-point value which might have a rounding error. I ran your code on my system and the results were correct. However, your code might generate different results on different platforms. And it seems that this is the case in your system.
Instead, you can do this:
#include <cstdio>
#include <array>
#include <span>
constexpr int convertDigitsToNumber( const std::span<const int> digits )
{
int resultNum { };
for ( const auto digit : digits )
{
resultNum = resultNum * 10 + digit;
}
return resultNum;
}
int main( )
{
constexpr std::size_t arraySize { 5 };
// use std::array instead of raw arrays
constexpr std::array<int, arraySize> arrayOfDigits { 4, 5, 6, 7, 8 };
constexpr int num { convertDigitsToNumber( arrayOfDigits ) };
std::printf( "%d\n", num );
return 0;
}
As a result of using constexpr keyword, the above function will be evaluated at compile-time (whenever possible, which is the case in the above code).
Note regarding constexpr: Use const and constexpr keywords wherever possible. It's a very good practice. Read about it here constexpr (C++).
Note: If you are not familiar with std::span then check it out here.

Formatting Commas into a long long integer

this is my first time posting a question. I was hoping to get some help on a very old computer science assignment that I never got around to finishing. I'm no longer taking the class, just want to see how to solve this.
Read in an integer (any valid 64-bit
integer = long long type) and output the same number but with commas inserted.
If the user entered -1234567890, your program should output -1,234,567,890. Commas
should appear after every three significant digits (provided more digits remain) starting
from the decimal point and working left toward more significant digits. If the number
entered does not require commas, do not add any. For example, if the input is 234 you
should output 234. The input 0 should produce output 0. Note in the example above
that the number can be positive or negative. Your output must maintain the case of the
input.
I'm relatively new to programming, and this was all I could come up with:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n;
cout << "Enter an integer:" << endl;
cin >> n;
int ones = n % 10;
int tens = n / 10 % 10;
int hund = n / 100 % 10;
int thous = n / 1000 % 10;
int tthous = n / 10000 % 10;
cout << tthous << thous << "," << hund << tens << ones << endl;
return 0;
}
The original assignment prohibited the use of strings, arrays, and vectors, so please refrain from giving suggestions/solutions that involve these.
I'm aware that some sort of for-loop would probably be required to properly insert the commas in the necessary places, but I just do not know how to go about implementing this.
Thank you in advance to anyone who offers their help!
Just to give you an idea how to solve this, I've maiden a simple implementation. Just keep in mind that is just a simple example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n = -1234567890;
if ( n < 0 )
cout << '-';
n = abs(n);
for (long long i = 1000000000000; i > 0; i /= 1000) {
if ( n / i <= 0 ) continue;
cout << n / i ;
n = n - ( n / i) * i;
if ( n > 0 )
cout << ',';
}
return 0;
}
http://coliru.stacked-crooked.com/a/150f75db89c46e99
The easy solution would be to use ios::imbue to set a locale that would do all the work for you:
std::cout.imbue(std::locale(""));
std::cout << n << std::endl;
However, if the restraints don't allow for strings or vectors I doubt that this would be a valid solution. Instead you could use recursion:
void print(long long n, int counter) {
if (n > 0) {
print(n / 10, ++counter);
if (counter % 3 == 0) {
std::cout << ",";
}
std::cout << n%10;
}
}
void print(long long n) {
if (n < 0) {
std::cout << "-";
n *= -1;
}
print(n, 0);
}
And then in the main simply call print(n);
A small template class comma_sep may be a solution, the usage may be as simple as:
cout << comma_sep<long long>(7497592752850).sep() << endl;
Which outputs:
7,497,592,752,850
Picked from here:
https://github.com/arloan/libimsux/blob/main/comma_sep.hxx
template <class I = int, int maxdigits = 32>
class comma_sep
char buff[maxdigits + maxdigits / 3 + 2];
char * p;
I i;
char sc;
public:
comma_sep(I i, char c = ',') : p(buff), i(i), sc(c) {
if (i < 0) {
buff[0] = '-';
*++p = '\0';
}
}
const char * sep() {
return _sep(std::abs(i));
}
private:
const char * _sep(I i) {
I r = i % 1000;
I n = i / 1000;
if (n > 0) {
_sep(n);
p += sprintf(p, "%c%03d", sc, (int)r);
*p = '\0';
} else {
p += sprintf(p, "%d", (int)r);
*p = '\0';
}
return buff;
}
};
The above class handles only integeral numbers, float/double numbers need to use a partial specialized version:
template<int maxd>
class comma_sep<double, maxd> {
comma_sep<int64_t, maxd> _cs;
char fs[64];
double f;
public:
const int max_frac = 12;
comma_sep(double d, char c = ',') : _cs((int64_t)d, c) {
double np;
f = std::abs(modf(d, &np));
}
const char * sep(int frac = 3) {
if (frac < 1 || frac > max_frac) {
throw std::invalid_argument("factional part too too long or invalid");
}
auto p = _cs.sep();
strcpy(fs, p);
char fmt[8], tmp[max_frac+3];
sprintf(fmt, "%%.%dlf", frac);
sprintf(tmp, fmt, f);
return strcat(fs, tmp + 1);
}
};
The two above classes can be improved by adding type-traits like std::is_integral and/or std::is_floating_point, though.

C++: Format String Containing Hex Value

Working with C++ on Visual Studio 2010.
Trying to come up with a robust function that will take a hex value as string and size as integer and then output the formatted hex value.
For e.g.,
If the input string is "A2" and size is 1, then the output is "0xA2"
If the input string is "800" and size is 2, then the output is "0x0800"
If the input string is "DEF" and size is 4, then the output is "0x00000DEF"
If the input string is "00775" and size is 4, then the output is "0x00000775"
If the input string is "FB600" and size is 3, then the output is "0x0FB600"
The basic idea is, multiply size by 2 and then if the string length is less than that, then add leading zeros to the hex value and then append it with "0x".
"0x" is appended irrespective of whether leading zeros are added.
As you see in 1st example, there's no zeros to add as the string already contains 2 characters.
I came up with below function, but it's having memory corruption. Also when i try to process large amount of data by calling this function few hundrend times, it crashes. Seems my logic has memory holes in it.
So am hoping that someone can come up with a robust intelligent code for this function.
What i tried:
void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
int len = size * 2;
int diff = len - strlen(inputHex);
char * tempHex = new char [diff + 2]; //"2" is for holding "0x"
tempHex[0] = '0';
tempHex[1] = 'x';
if (len > strlen(inputHex))
{
for (int i = 2; i < ((len - strlen(inputHex)) + 2); i++)
{
tempHex[i] = '0';
}
}
strcat(tempHex, inputHex);
sprintf(outputFormattedHex, "%s", tempHex);
delete [] tempHex;
cout <<outputFormattedHex <<endl;
}
int main
{
char bbb1[24];
formatHexString("23", 1, bbb1);
char bbb2[24];
formatHexString("A3", 2, bbb2);
char bbb3[24];
formatHexString("0AA23", 4, bbb3);
char bbb4[24];
formatHexString("7723", 4, bbb4);
char bbb5[24];
formatHexString("AA023", 4, bbb5);
return 0;
}
UPDATED:
I cannot modify the arguments to original function as this function is called from a different application. So i modified my original function with your code, but this is not working. Any ideas?
void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
string input(inputHex);
std::size_t const input_len(input.length());
if (!size || (size * 2 < input_len))
size = input_len / 2 + input_len % 2;
std::stringstream ss;
ss << "0x" << std::setw(2 * size) << std::setfill('0') << input;
sprintf(outputFormattedHex, "%s", ss.str());
}
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <cstddef>
std::string formatHexString(std::string const & input, std::size_t size = 0)
{
std::size_t const input_len(input.length());
// always round up to an even count of digits if no size is specified
// or size would cause the output to be truncated
if (!size || (size * 2 < input_len))
size = input_len / 2 + input_len % 2;
std::stringstream ss;
ss << "0x" << std::setw(2 * size) << std::setfill('0') << input;
return ss.str();
}
int main()
{
std::cout << formatHexString( "23") << '\n'
<< formatHexString( "A3", 2) << '\n'
<< formatHexString( "AA23", 4) << '\n'
<< formatHexString( "7723", 4) << '\n'
<< formatHexString("AA023", 4) << '\n';
}
Solution without std::stringstream:
#include <string>
#include <cstddef>
std::string formatHexString(std::string const & input, std::size_t size = 0)
{
std::size_t const input_len(input.length());
// always round up to an even count of digits if no size is specified
// or size would cause the output to be truncated
if (!size || (size * 2 < input_len))
size = input_len / 2 + input_len % 2;
std::string result("0x");
for (std::size_t i = 0, leading_zeros = size * 2 - input_len; i < leading_zeros; ++i)
result += '0';
result += input;
return result;
}
Updated:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <cstddef>
#include <cstdio>
void formatHexString(char const * inputHex, int size, char * outputFormattedHex)
{
int const input_len(std::strlen(inputHex));
if (!size || (size * 2 < input_len))
size = input_len / 2 + input_len % 2;
std::stringstream ss;
ss << "0x" << std::setw(2 * size) << std::setfill('0') << inputHex;
std::strcpy(outputFormattedHex, ss.str().c_str());
}
int main()
{
char output[24];
formatHexString("23", 1, output);
std::cout << output << '\n';
formatHexString("A3", 2, output);
std::cout << output << '\n';
formatHexString("0AA23", 4, output);
std::cout << output << '\n';
formatHexString("7723", 4, output);
std::cout << output << '\n';
formatHexString("AA023", 4, output);
std::cout << output << '\n';
}
It is unclear from your question, what you expect to happen with leading zeros on the input: I.e. either input "00000000EA" Size 2 turns to "00EA", or it keeps all its leading zeros.
This simple solution is for both cases (bTrim = true, for the 1st case):
#include <string>
void formatHexString(std::string & strHex, unsigned int nSize, bool bTrim = true)
{
if (bTrim) // Trim leading-zeros:
strHex = strHex.substr(strHex.find_first_not_of('0'));
if (nSize > strHex.length()) // Pad with leading-zeros to fit nSize:
strHex.insert(0, std::string(nSize - strHex.length(), '0').c_str());
strHex.insert(0, "0x"); // Insert prefix
}
-
If it's important to keep the original signature, wrap the above formatHexString with:
void formatHexString(char* inputHex, int size, char* outputFormattedHex)
{
std::string strHex(inputHex);
formatHexString(strHex, size * 2);
strcpy_s(outputFormattedHex, strHex.length()+1, strHex.c_str()); // Visual Studio
}

Karatsuba Integer Multiplication failing with segmentation fault

As I run the program, it crashes with segmentation fault. Also, when I debug the code in codeblocks IDE, I am unable to debug it as well. The program crashes even before debugging begins. I am not able to understand the problem. Any help would be appreciated. Thanks!!
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
// Method to make strings of equal length
int makeEqualLength(string& fnum,string& snum){
int l1 = fnum.length();
int l2 = snum.length();
if(l1>l2){
int d = l1-l2;
while(d>0){
snum = '0' + snum;
d--;
}
return l1;
}
else if(l2>l1){
int d = l2-l1;
while(d>0){
fnum = '0' + fnum;
d--;
}
return l2;
}
else
return l1;
}
int singleDigitMultiplication(string& fnum,string& snum){
return ((fnum[0] -'0')*(snum[0] -'0'));
}
string addStrings(string& s1,string& s2){
int length = makeEqualLength(s1,s2);
int carry = 0;
string result;
for(int i=length-1;i>=0;i--){
int fd = s1[i]-'0';
int sd = s2[i]-'0';
int sum = (fd+sd+carry)%10+'0';
carry = (fd+sd+carry)/10;
result = (char)sum + result;
}
result = (char)carry + result;
return result;
}
long int multiplyByKaratsubaMethod(string fnum,string snum){
int length = makeEqualLength(fnum,snum);
if(length==0) return 0;
if(length==1) return singleDigitMultiplication(fnum,snum);
int fh = length/2;
int sh = length - fh;
string Xl = fnum.substr(0,fh);
string Xr = fnum.substr(fh,sh);
string Yl = snum.substr(0,fh);
string Yr = snum.substr(fh,sh);
long int P1 = multiplyByKaratsubaMethod(Xl,Yl);
long int P3 = multiplyByKaratsubaMethod(Xr,Yr);
long int P2 = multiplyByKaratsubaMethod(addStrings(Xl,Xr),addStrings(Yl,Yr)) - P1-P3;
return (P1*pow(10,length) + P2*pow(10,length/2) + P3);
}
int main()
{
string firstNum = "62";
string secondNum = "465";
long int result = multiplyByKaratsubaMethod(firstNum,secondNum);
cout << result << endl;
return 0;
}
There are three serious issues in your code:
result = (char)carry + result; does not work.The carry has a value between 0 (0 * 0) and 8 (9 * 9). It has to be converted to the corresponding ASCII value:result = (char)(carry + '0') + result;.
This leads to the next issue: The carry is even inserted if it is 0. There is an if statement missing:if (carry/* != 0*/) result = (char)(carry + '0') + result;.
After fixing the first two issues and testing again, the stack overflow still occurs. So, I compared your algorithm with another I found by google:Divide and Conquer | Set 4 (Karatsuba algorithm for fast multiplication)(and possibly was your origin because it's looking very similar). Without digging deeper, I fixed what looked like a simple transfer mistake:return P1 * pow(10, 2 * sh) + P2 * pow(10, sh) + P3;(I replaced length by 2 * sh and length/2 by sh like I saw it in the googled code.) This became obvious for me seeing in the debugger that length can have odd values so that sh and length/2 are distinct values.
Afterwards, your program became working.
I changed the main() function to test it a little bit harder:
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
string intToStr(int i)
{
string text;
do {
text.insert(0, 1, i % 10 + '0');
i /= 10;
} while (i);
return text;
}
// Method to make strings of equal length
int makeEqualLength(string &fnum, string &snum)
{
int l1 = (int)fnum.length();
int l2 = (int)snum.length();
return l1 < l2
? (fnum.insert(0, l2 - l1, '0'), l2)
: (snum.insert(0, l1 - l2, '0'), l1);
}
int singleDigitMultiplication(const string& fnum, const string& snum)
{
return ((fnum[0] - '0') * (snum[0] - '0'));
}
string addStrings(string& s1, string& s2)
{
int length = makeEqualLength(s1, s2);
int carry = 0;
string result;
for (int i = length - 1; i >= 0; --i) {
int fd = s1[i] - '0';
int sd = s2[i] - '0';
int sum = (fd + sd + carry) % 10 + '0';
carry = (fd + sd + carry) / 10;
result.insert(0, 1, (char)sum);
}
if (carry) result.insert(0, 1, (char)(carry + '0'));
return result;
}
long int multiplyByKaratsubaMethod(string fnum, string snum)
{
int length = makeEqualLength(fnum, snum);
if (length == 0) return 0;
if (length == 1) return singleDigitMultiplication(fnum, snum);
int fh = length / 2;
int sh = length - fh;
string Xl = fnum.substr(0, fh);
string Xr = fnum.substr(fh, sh);
string Yl = snum.substr(0, fh);
string Yr = snum.substr(fh, sh);
long int P1 = multiplyByKaratsubaMethod(Xl, Yl);
long int P3 = multiplyByKaratsubaMethod(Xr, Yr);
long int P2
= multiplyByKaratsubaMethod(addStrings(Xl, Xr), addStrings(Yl, Yr))
- P1 - P3;
return P1 * pow(10, 2 * sh) + P2 * pow(10, sh) + P3;
}
int main()
{
int nErrors = 0;
for (int i = 0; i < 1000; i += 3) {
for (int j = 0; j < 1000; j += 3) {
long int result
= multiplyByKaratsubaMethod(intToStr(i), intToStr(j));
bool ok = result == i * j;
cout << i << " * " << j << " = " << result
<< (ok ? " OK." : " ERROR!") << endl;
nErrors += !ok;
}
}
cout << nErrors << " error(s)." << endl;
return 0;
}
Notes about changes I've made:
Concerning std library: Please, don't mix headers with ".h" and without. Every header of std library is available in "non-suffix-flavor". (The header with ".h" are either C header or old-fashioned.) Headers of C library have been adapted to C++. They have the old name with prefix "c" and without suffix ".h".
Thus, I replaced #include <math.h> by #include <cmath>.
I couldn't resist to make makeEqualLength() a little bit shorter.
Please, note, that a lot of methods in std use std::size_t instead of int or unsigned. std::size_t has appropriate width to do array subscript and pointer arithmetic i.e it has "machine word width". I believed a long time that int and unsigned should have "machine word width" also and didn't care about size_t. When we changed in Visual Studio from x86 (32 bits) to x64 (64 bits), I learnt the hard way that I had been very wrong: std::size_t is 64 bits now but int and unsigned are still 32 bits. (MS VC++ is not an exception. Other compiler vendors (but not all) do it the same way.)I inserted some C type casts to remove the warnings from compiler output. Such casts to remove warnings (regardless you use C casts or better the C++ casts) should always be used with care and should be understood as confirmation: Dear compiler. I see you have concerns but I (believe to) know and assure you that it should work fine.
I'm not sure about your intention to use long int in some places. (Probably, you transferred this code from original source without caring about.) As your surely know, the actual size of all int types may differ to match best performance of the target platform. I'm working on a Intel-PC with Windows 10, using Visual Studio. sizeof (int) == sizeof (long int) (32 bits). This is independent whether I compile x86 code (32 bits) or x64 code (64 bits). The same is true for gcc (on cygwin in my case) as well as on any Intel-PC with Linux (AFAIK). For a granted larger type than int you have to choose long long int.
I did the sample session in cygwin on Windows 10 (64 bit):
$ g++ -std=c++11 -o karatsuba karatsuba.cc
$ ./karatsuba
0 * 0 = 0 OK.
0 * 3 = 0 OK.
0 * 6 = 0 OK.
etc. etc.
999 * 993 = 992007 OK.
999 * 996 = 995004 OK.
999 * 999 = 998001 OK.
0 error(s).
$

convert vector of char to an int

I need to convert a part of vectors of chars to an int.
If I have
std::vector<char> // which contains something like asdf1234dsdsd
and I want to take characters from the 4th till 7th position and convert it into an int.
The positions are always known.
How do I do it the fastest way ?
I tried to use global copy and got a weird answer. Instead of 2 I got 48.
If the positions are known, you can do it like this
int x = (c[4] - '0') * 1000 + (c[5] - '0') * 100 + (c[6] - '0') * 10 + c[7] - '0';
This is fairly flexible, although it doesn't check for overflow or anything fancy like that:
#include <algorithm>
int base10_digits(int a, char b) {
return 10 * a + (b - '0');
}
int result = std::accumulate(myvec.begin()+4, myvec.begin()+8, 0, base10_digits);
The reason copying didn't work is probably because of endianness, assuming the first char is the most significant:
int x = (int(c[4]) << 24) + (int(c[5]) << 16) + (int(c[6]) << 8) + c[7]
1.Take the address of the begin and end (one past the end) index.
2.Construct a std::string from it.
3.Feed it into a std::istringstream.
4.Extract the integer from the stringstream into a variable.
(This may be a bad idea!)
Try this:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int vtoi(vector<char> vec, int beg, int end) // vector to int
{
int ret = 0;
int mult = pow(10 , (end-beg));
for(int i = beg; i <= end; i++) {
ret += (vec[i] - '0') * mult;
mult /= 10;
}
return ret;
}
#define pb push_back
int main() {
vector<char> vec;
vec.pb('1');
vec.pb('0');
vec.pb('3');
vec.pb('4');
cout << vtoi(vec, 0, 3) << "\n";
return 0;
}
long res = 0;
for(int i=0; i<vec.size(); i++)
{
res += vec[i] * pow (2, 8*(vec.size() - i - 1)); // 8 means number of bits in byte
}