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。(还为不同的基数提供了其他有趣的结果)

缺陷在哪里?

4

1 回答 1

4

您正在按位置递增指向空字符串的指针u%base,然后使用它来构造 a std::string,它会查找空终止符。这会导致未定义的行为。立即使用std::string

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

接下来,没有从intto的转换std::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;
    }
}
于 2013-05-18T23:46:50.487 回答