2013-05-18 15 views
0

我創建了一個函數,它將數字轉換爲給定基數的等價物並將其打印到字符串中。它看起來像無瑕疵,但給出了荒謬的結果。下面的代碼應該將100轉換爲9,並給出「121」。字符串指針中有趣的錯誤

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 
void doldur(string *s,int u,int base){ 
    *s=""; 
    while(u!=0){ 
     *s=""+u%base+*s; 
     u/=base; 
    } 
    return; 
} 
int main() { 
    ofstream fout ("dualpal.out"); 
    ifstream fin ("dualpal.in"); 
    int i; 
    string hey; 
    doldur(&hey,100,9); 
    cout<<hey; 
    cin>>i; 
    return 0; 
} 

但可笑的是,它打印dualpal.outualpal.outdualpal.out。(對於不同的基地也給其他有趣的結果)

哪裏缺陷?

+1

''''不是'std :: string'類型。 – chris

+0

如果你從不使用它們,你爲什麼要聲明'fout'和'fin'? – jwodder

+1

具體而言,它在這一行很重要:'* s =「」+ u%base + * s;' – wjl

回答

4

您正在通過u%base位置遞增指向空字符串的指針,然後使用它構造std::string,該查找結果爲空終止符。這會導致未定義的行爲。使用std::string蝙蝠:

*s = std::string() + ...; 

下,有從intstd::string任何轉換。使用功能類似std::to_string

*s = std::to_string(u%base) + *s; 

第一個操作數是現在沒有意義的,所以我刪除它。最後,所有的解引用都有點令人厭煩,不是嗎?我會做一個並返回它:

std::string doldur(const std::string &s,int u,int base){ 
    std:string ret; 
    while(u!=0){ 
     ret = std::to_string(u%base) + ret; 
     u/=base; 
    } 
    return ret; 
} 

不要擔心返回的任何性能損失。或者使用參考並根據需要更改原始內容:

void doldur(std::string &s,int u,int) { 
    s.clear(); 
    while(u!=0){ 
     s = std::to_string(u%base) + s; 
     u/=base; 
    } 
}