How to add a number to an integer like a string - c++

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 ;
}

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.

Integer value assignment in c++

I'm pretty new to C++ and I have the following simple program:
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
I receive always the output 15, although I've changed the value of b to 6.
Thanks in advance for your answers!
Execution of your code is linear from top to bottom.
You modify b after you initialize sum. This modification doesn't automatically alter previously executed code.
int sum = a + b; writes the result of adding a and b into the new variable sum. It doesn't make sum an expression that always equals the result of the addition.
There are already answers, but I feel that something is missing...
When you make an assignment like
sum = a + b;
then the values of a and b are used to calculate the sum. This is the reason why a later change of one of the values does not change the sum.
However, since C++11 there actually is a way to make your code behave the way you expect:
#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
This will print :
11
This line
auto sum = [&](){return a + b;};
declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write sum() then a and b are used to calculate the sum. Because a and b are captured by reference (thats the meaning of the &), sum() uses the current values of a and b and not the ones they had when you declared the lambda. So the code above is more or less equivalent to
int sum(int a, int b){ return a+b;}
int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}
You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}

Storing output from setfill and setw to a string

I am trying to produce binary numbers using C's itoa function and C++ setfill and setw function. If I use only itoa, the output displayed does not have proper 0 padding.
This is a small code snippet.
int s = 8;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
cout<<setfill('0')<<setw(3)<<endl;
cout<<buffer<<endl;
}
Now it does a great job in printing out the output.
If I hadn't used setfill and setw, the formatting would have been something like
1
10
11
100
101
110
111
instead of
001
010
011
100
101
110
111
Now I want to store the padded binary numbers produced and store it into a vector. Is it possible?
I think I have got a solution using bitset, and it works fine.
std::ostringstream oss;
int s = 3;
for (int i = 1; i<s;i++)
{
itoa(i,buffer,2);
oss<<setfill('0')<<setw(3);
oss<<buffer;
string s = oss.str();
cout<<s<<'\n'<<endl;
};
However, I just want to point out that the solution I obtained looks some this!
Can it manipulated by flushing out streams in consecutive iterations. Its just an afterthought.
Consider using a bitset instead of itoa:
#include <bitset>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> binary_representations;
int s = 8;
for (int i = 1; i < s; i++)
{
binary_representations.push_back(std::bitset<3>(i).to_string());
}
}
EDIT: If you need a variable length, one possibility is
// Note: it might be better to make x unsigned here.
// What do you expect to happen if x < 0?
std::string binary_string(int x, std::size_t len) {
std::string result(len, '0');
for(std::string::reverse_iterator i = result.rbegin(); i != result.rend(); ++i) {
*i = x % 2 + '0';
x /= 2;
}
return result;
}
and then later
binary_representations.push_back(binary_string(i, 3));

C++ easy way to convert int to string with unknown base

Here is code in Java:
int a = 456;
int b = 5;
String s = Integer.toString(a, b);
System.out.println(s);
Now I want the same in C++, but all the conversions i find convert to base 10 only. I ofc dont want to implement this by mysleft, why to write something what already exists
although std::strtol is more flexible, in a controlled case you can use itoa as well.
int a = 456;
int b = 5;
char buffer[32];
itoa(a, buffer, b);
If you want base 8 or 16 you can easily use the string manipulators std::oct and std::hex. If you want arbitrary bases, I suggest checking out this question.
Without error handling http://ideone.com/nCj2XG:
char *toString(unsigned int value, unsigned int radix)
{
char digit[] = "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ";
char stack[32];
static char out[33];
int quot, rem;
int digits = 0;
do
{
quot = value / radix;
rem = value % radix;
stack[digits] = digit[rem];
value = quot;
digits++;
}
while( value );
int i = 0;
while(digits--)
{
out[i++] = stack[digits];
}
out[i] = 0;
return out;
}
There is no standard function itoa, which performs conversion to an arbitrary calculus system. But for example, in my version of the compiler there is no implementation. My solution:
#include <string>
// maximum radix - base36
std::string int2string(unsigned int value, unsigned int radix) {
const char base36[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string result;
while (value > 0) {
unsigned int remainder = value % radix;
value /= radix;
result.insert(result.begin(), base36[remainder]);
}
return result;
}

putting an integer into a string

I'm trying to put an integer into a string by separating its digits and putting them by order in a string of size 3
this is my code:
char pont[4];
void convertInteger(int number){
int temp100=0;
int temp10=0;
int ascii100=0;
int ascii10=0;
if (number>=100) {
temp100=number%100;
ascii100=temp100;
pont[0]=ascii100+48;
number-=temp100*100;
temp10=number%10;
ascii10=temp10;
pont[1]=ascii10+48;
number-=temp10*10;
pont[2]=number+48;
}
if (number>=10) {
pont[0]=48;
temp10=number%10;
ascii10=temp10;
pont[1]=ascii10+48;
number-=temp10*10;
pont[2]=number+48;
}
else{
pont[0]=48;
pont[1]=48;
pont[2]=number+48;
}
}
here's an example of what's suppose to happen:
number = 356
temp100 = 356%100 = 3
ascii100 = 3
pont[0]= ascii100 = 3
temp100 = 3*100 = 300
number = 365 - 300 = 56
temp10 = 56%10 = 5
ascii10 = 5
pont[1]= ascii10 = 5
temp10 = 5*10 = 50
number = 56 - 50 = 6
pont[2]=6
I might have an error somewhere and not seeing it (don't know why) ...
This is suppose to be C++ by the way. I might be mixing this up with C language...
Thanks in advance
Probably the mistake that you're overlooking right now:
pont[2]=number+48;
}
if (number>=10) { /* should be else if */
pont[0]=48;
However, I'd like to suggest a different approach; you don't care that the value is above 100, 10, etc., as 0 is still a useful value -- if you don't mind zero-padding your answer.
Consider the following numbers:
int hundreds = (number % 1000) / 100;
int tens = (number % 100) / 10;
int units = (number % 10);
All built-in types know how to represent themselves to std::ostream. They can be formatted for precision, converted to different representations, etc.
This uniform handling allows us to write built-ins to the standard output:
#include <iostream>
int main()
{
std::cout << 356 << std::endl; // outputting an integer
return 0;
}
Output:
356
We can stream to more than just cout. There is a standard class called std::ostringstream, which we can use just like cout, but it gives us an object which can be converted to a string, rather than sending everything to standard output:
#include <sstream>
#include <iostream>
int main()
{
std::ostringstream oss;
oss << 356;
std::string number = oss.str(); // convert the stream to a string
std::cout << "Length: " << number.size() << std::endl;
std::cout << number << std::endl; // outputting a string
return 0;
}
Output:
Length: 3
356