为什么这个C++程序在某些编译器中有效但在其他编译器中却不行?c ++编译器之间的主要区别是什么?

abr*_*dha -2 c++ g++ clang visual-c++ compiler-specific

我已经为我的班级写了这个程序.我发现它使用GNU g ++编译器编译并运行得很好.我的教授从他的网站自动评分我们的程序,该网站使用Microsoft Visual Studio编译器,它会引发错误.我也在BSD clang编译器中尝试过这个程序,我得到了一个完全不同的错误.

#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>

using namespace std;
double dec2Bin(int value, char binaryString[])
{
    int x = 1;
    string hold = "";
    while(x <= value){
        x *= 2;
    }
    x /= 2;

    while(x >= 1){
        //cout << x << " ";
        if(value > x){
            hold += "1";
            value -= x;
        }
        else if(value < x){
            hold += "0";
        }
        else if(value == x){
            hold += "1";
            value = 0;
            //return hold;
        }
        x /= 2;

        //cout << hold << endl;
    }
    return atoi(hold);

}
int main()
{
    char binstr[100];
    int num = 0;
    cout << "Enter a decimal string: ";
    cin >> num;
    cout << "its "<<dec2Bin(num, binstr) << endl;

}
Run Code Online (Sandbox Code Playgroud)

是什么让所有这些编译器如此不同?有什么我可以做的,以确保我的代码可以在任何编译器中工作?

πάν*_*ῥεῖ 5

"是什么让所有这些编译器如此不同?我能做些什么来确保我的代码能在任何编译器中运行吗?"

该程序代码实际上不适用于任何c ++编译器.如果你有一个编译程序而没有抛出任何错误或警告,它有一个严重的错误(另一个怀疑可能是,你没有在这里显示你的原始代码).

当我在Ideone上编译您的程序时,我收到以下错误消息

prog.cpp:34:21: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
Run Code Online (Sandbox Code Playgroud)

这表明你应该使用

 return atoi(hold.c_str());
Run Code Online (Sandbox Code Playgroud)

因为std::string没有自动转换为const char*.提到的std::string::c_str()功能就是这样做的.

你也一直缺席#include <string>,而不是using namespace std;你应该更明确地写std::string.

这是代码编译干净版本.