I have 2 integers 1 and 001 how do i make it 1001? Tried to convert both numbers into string using to_string and concatenated and again did stoi but this returns 11 not 1001.
Show your context. At the moment you haven't shown any requirement to do arithmetic, so you could just input two std::string and output them as the concatenation.
this looks like you are asking the wrong question.
what do you have, what do you want to accomplish?
because to-string and back is very inefficient if you have 2 ints and just want to jack them together. But if you have 2 ints, you may need to think in binary/bits instead of base 10? because, at the moment, you have 1 representing 1 and 1 representing 8. Do you know that the one that represents 8 is 8? If so, just add them. 8+1 is 1001 is 9.
> I have 2 integers 1 and 001 how do i make it 1001?
I'm guessing the OP read in a country code and a phone number as integers, and now wants to construct a proper IDD number out of the resulting mess.
Those are the same number. So is 01, 0001 and 000000000000000000000000000000000000000000000001.
What makes the second number 001 one of the others? I the real problem to concatenate a single digit to a 3-digit number, padded with zeros if needed? Or some other requirement?
@Scarletpimp, why the reluctance to show what you've tried to code so far? This is a rather trivial use of std::string and a couple of numeric conversion functions in the <string> header.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string>
int main()
{
int a { 1 };
int b { 1 };
std::string str_num { std::to_string(a) + "00" + std::to_string(b) };
std::cout << str_num << '\n';
int num { std::stoi(str_num) };
std::cout << num << '\n';
}
001 is not an integer, it is a string construct based on an integer of 1.
sorry i was looking for a way to concatenate integer 1 and another 0 padded number 001. so its like i will get this 2nd part as input and have to pad with zeroes which i have done with below code. I was looking for a way to concatenate these integer and padded value. I found the solution now.
int x = 1;
ostringstream ret;
ret << setw(3) << setfill('0') << x;
int test = stoi(to_string(1) + ret.str());
now test has 1001 which is what i was looking for. Thanks everyone for the hints.