Reputation: 131
I have problem with concatenating two strings in C++. What I want to do is to convert a binary number inputted by the user and align its length so that I can further add two numbers inputted. I'm using array of string for input purpose:
char* num1, num2;
For example user types two numbers:
100010
1010
And I want to process them with the following structure:
100010
001010
Depending on which string is longer in loop I create another string where I add missing zeros:
char temp2[x];
for (int i=0; i <(x-y); i++) //x,y is strlen(num1 or num2)
temp2[i]=48;
strcat(temp2, num2);
Unfortunately some strange characters appear between two strings and the second string looks like:
00d↑ą,@1010 not simply 001010
Later on I wanted to convert this string into array of int thus I could use full adder algorithm:
for(i = 0; i < lengthofString ; i++){
sum[i] = ((a[i] ^ b[i]) ^ c); // c is carry
c = ((a[i] & b[i]) | (a[i] & c)) | (b[i] & c);
}
Advises on how to solve the problem of adding two different sizes binary numbers are also really welcome.
EDIT: OK, so I tried to follow using std::bitset library but I have no clue whether any piece of code I wrote is correct. Unfortunately I have no access to compiler now (using Android tablet). Result of my work:
#include <bitset>
#include <iostream>
#include "binary.h"
using namespace std;
void binary::add(string string1, string string2){
cin >> string1;
cin >> string2;
bitset<20> num1 (string1);
bitset<20> num2 (string2);
// not sure how to use loop operators with bitset as it's my very first piece of code and do I need to assign "c" argument first?
for(int i = 0; i < 20 ; i++){
sum[i] = ((num1[i] ^ num2[i]) ^ c); // c is carry
c = ((num1[i] & num2[i]) | (num1[i] & c)) | (num2[i] & c);
}
for (int j=0; i < 20; j++)
cout << sum[j];
}
Upvotes: 0
Views: 729
Reputation: 46
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
using namespace std;
main ()
{
ostringstream os;
istringstream is;
float num=0;
int a=8;
b=6;
cin >>a>>b;
os << a << "."<< b;
is(os.str());
is >> num;
cout << num;
cout << num * 2;
return 0;
}
Upvotes: 0