When I try to make integers using the rand() function, I cannot include them in a string. These are the two codes that I have tried:
int x1, x2;
x1 = (rand() % 14 + 2);
x2 = (rand() % 14 + 2);
char c1 = char(x1);
char c2 = char(x2);
string Hand = {c1, c2};
cout << Hand << endl;
I don't get any errors with this one, but it doesn't run. This is the one I thought would be correct:
int c1, c2;
c1 = (rand() % 14 + 2);
c2 = (rand() % 14 + 2);
to_string(c1);
to_string(c2);
string Hand = {c1[0], c2[0]};
cout << Hand << endl;
Yet it isn't. This must be really simple. How is it done?
Note that c1 and c2 are not vectors, so c1[0] make no sense.
The to_string method returns a string, don´t turns the argument into one. That said, the code could work better like this:
int c1, c2;
c1 = (rand() % 14 + 2);
c2 = (rand() % 14 + 2);
string Hand = {to_string(c2)[0], to_string(c1)[0]};
cout << Hand << endl;
Try something like this:
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <string>
#include <sstream>
using namespace std;
int main() {
// your code goes here
std::ostringstream ss;
int x1, x2;
x1 = (rand() % 14 + 2);
x2 = (rand() % 14 + 2);
ss << x1 << x2;
std::string Hand = ss.str();
cout << Hand << endl;
return 0;
}
C++ is statically typed language. std::to_string won't change the type... It returns the string.
As for the first code, you're dealing with non-printable characters.
Related
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);
How do I change the following program, so that it performs the same Task, but using only additions and assignments?
I can only do max 27 additions, and the Output has to be generated in a single Input.
Loops and other control flow operations are not allowed
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
std::cout << a*29 << std::endl;
return 0;
}
Another approach that requires 7 +:
int M1 = a; // 1a
int M2 = M1 + M1; // 2a
int M4 = M2 + M2; // 4a
int M8 = M4 + M4; // 8a
int M16 = M8 + M8; // 16a
int res = M16 + M8 + M4 + M1; // 29a
The result is constructed from the binary pattern of the multiplier, i.e. 29 decimal is 0001.1101 binary. So we need to add M16, M8, M4 and M1 (and exclude M2).
This is not general, and it cannot be, but to multiply just by 29 you can do this:
// x is input
int t = x; // x*1
x = x + x;
x = x + x;
t = t + x; // x*5
x = x + x;
t = t + x; // x*13
x = x + x;
t = t + x; // x*29
This is just unrolled binary multiplication, like the similar answers, but without naming the temporary results. The additions to t correspond to the set bits in 29.
This way you can do it with 21 additions.
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
int b = (a+a+...+a) // 10 times
b = b + b;
b = b + (a + a + a ... + a ); // 9 times
std::cout << b << std::endl;
return 0;
}
Can you use an additional var?
b = a + a + a//3 times a
b = b + b + b//9 times a
b = b + b + b//27 times a
b = b + a + a//29 times a
Multiplication is just a repeated addition. Use a loop for this. Do you know how many times your loop should execute? Yes! So use a for loop.
So here is the plan:
Get input
Use a for loop to perform the addition
Output sum
Example:
// get input
int input;
std::cout << "Enter number: ";
std::cin >> input;
// use a for loop to perform the addition
int sum = 0;
for(int i = 0; i< 29; ++i)
sum += a;
// output result
std::cout << sum << std::endl;
,resRepetitive addition is multiplication -- mathematically
So repeat addition of a for n number of times. A simple for/while loop can do this
#include <iostream>
int main()
{
int a,i,temp=0;
std::cout << "Enter number: ";
std::cin >> a;
for(i=1;i<=29;i++)
temp+=a;//add a repeatedly for 'n' number of times. Here 29 as per your requirement. a*n
std::cout << temp <<std::endl;
return 0;
}
Without loop
int b=0,result=0;
b=a+a+a+a+a+a+a;\\adding for 7 times
result=b+b+b+b+a;\\4 times 7 (of a)= 28+a= 29 times (of a).
This involves 10 addition.
You can try this -
b = a + a + a + a + a + a + a + a + a + a + a + a + a + a + a; // equivalent to a*15
b += b -a;
If you are only allowed to use + and =, and are not allowed to cheat by introducing other variables, there is no way of doing this unless you indulge in a bit of undefined behaviour and allow yourself something of the form
... + (a += ...) + ...
where ... is any number of a +. The trick here is that (a += ...) changes the value of a part way through evaluation of the expression.
Tempting as it may be, alas this is not portable C++ since += and + are not sequencing points. On your classroom compiler, you might be able to get this to work.
See https://ideone.com/fC3fai, you can see that
(a + a + a + a + a + (a += a + a + a) + a + a + a + a + a)
does the job on that particular compiler (at the time of writing). (For what it's worth, it also does the correct thing in Java where the expression is well-defined).
You can add value multiple times:
int sum=0;
for(int i=0; i<multipler; i++){
sum+=a; //adds value of a to itself
}
return sum;
If you want to multiple only by 2 you can just shift left:
a = a << 1;
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).
$
In C++ I am trying to add two integers together. I don't want this:
5 + 5 = 10
I want it to be:
5 + 5 = 55
How can I add two integers together like strings. I know how to do this but it would be a lot of code and I'm just wondering if there's a short version under four lines.
Edit : Since Mingw doesn't properly support some C++11 features like to_string(), itoa() and that I'm looking for something that doesn't use a C++11 features.
If you want an int as result, multiply with the base:
int a = 5;
int b = 5;
int c = 10 * a + b; // 55
If you want the result to be a std::string, use std::to_string (since C++11):
int a = 5;
int b = 5;
std::string c = std::to_string(a) + std::to_string(b); // "55"
Before C++11, you can use a std::stringstream:
int a = 5;
int b = 5;
std::stringstream ss;
ss << a << b;
std::string c = ss.str(); // "55"
Try this:
#include<iostream>
using namespace std;
int main(){
int value1 = 5;
int value2 = 4;
string put_together = to_string(value1) + to_string(value2);
return 0 ;
}
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
}