2014-10-28 377 views
0

我在C++中連接兩個字符串時遇到問題。我想要做的是轉換用戶輸入的二進制數字並對齊其長度,以便我可以進一步添加兩個輸入的數字。我使用的字符串數組輸入目的:在C++中連接兩個字符串(二進制數加法)

char* num1, num2; 

例如用戶類型的兩個數字:

100010 
1010 

而且我想用下面的結構來處理它們:

100010 
001010 

根據循環中哪個字符串更長,我創建了另一個字符串,在其中添加缺失的零:

char temp2[x]; 
    for (int i=0; i <(x-y); i++) //x,y is strlen(num1 or num2) 
    temp2[i]=48; 
    strcat(temp2, num2); 

不幸的是一些奇怪的字符,兩個字符串和第二字符串看起來之間出現像:

00d↑ą,@1010 not simply 001010 

後來我想這個字符串轉換成整型數組這樣我可以使用全加器的算法:

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

如何解決添加兩個不同大小的二進制數字的問題的建議也非常受歡迎。

編輯: 好的,所以我試圖遵循使用std :: bitset庫,但我不知道我寫的任何一段代碼是否正確。不幸的是,我現在無法訪問編譯器(使用Android平板電腦)。我的工作的結果:

#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]; 

} 
+0

TEMP2不是0終結。 strcat會陷入困境,甚至可能會在前面的0字符中出現殘段。 – 2014-10-28 16:44:58

+1

這是用於教育目的?否則,我建議使用['std :: bitset'](http://en.cppreference.com/w/cpp/utility/bitset)和'std :: string'。 – 2014-10-28 16:45:08

+0

1)如何終止temp2字符串,使strcat不會搞砸? 2)你的意思是把每個角色都移到正確的位置,並在開始時加入「0」?沒有關於如何使用std :: bitset函數的線索,所以一些例子會很好,因爲我剛剛開始瞭解C++中的一些基礎知識。3)使用位集庫時,不同大小的二進制數不會有問題? – user4165421 2014-10-28 16:57:52

回答

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