将c风格的程序转换为c++

Converting a c style program to a c++

本文关键字:c++ 程序转换 风格      更新时间:2023-10-16

我有这个C风格的程序:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >=1; i >>= 1 ) {
        // Fixed Typo - Replaced a ; with the correct {
        if ( c & i ) {
            printf( "1" );
        } else {
            printf( "0" );
        }
    }
}
int main() {
    for ( int i = 0; i < 256; i++ ) {
        printf( "%3d = ", i );
        showOneByteBinaryNumber( i );
        printf( "n" );
     }
     return 0;
}

然后将程序修改为:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >= 1; i >>= 1 ) {
        if ( c & i ) {
            std::cout << 1;
        }
        else {
            std::cout << 0;
        }
    }
}
int main() {
    for ( int i = 0; i < 256; i++ ) {
        std::cout << "%3d = " << i;
        showOneByteBinaryNumber( i );
        std::cout << "n";
    }
    return 0;
}

我应该期望看到二进制值的表从0增加到255,但是当我尝试使用std::cout将其转换为c++等效版本时,我在输出中得到的其他数字不是0或1。

我不确定罪魁祸首是在改变的函数内还是在main中的for循环内。我不知道如何改变printf() "%3d"的参数;对std::cout

做同样的操作

是RamandepPunia为我提供了正确的答案!

在这行代码中:

printf( "%3d", i );

我试图用

替换它
std::cout << "%3d = " << i; // I did initially try std::setw( 3 ) but was giving wrong results;
std::cout << std::setw(3) << " = " << i;

他的注释代码:

std::cout << std::setw(3) << i << " = ";

是我正在寻找的,现在程序给了我正确的结果!

编辑

在我得到它的工作后,我确实修改了我的函数如下:

void showOneByteBinaryNumber( char c ) {
    for ( int i = 128; i >= 1; i >>= 1 ) {
        std::cout << ( (c & i) ? 1 : 0);
     }
}

然而,David C. Rankin也给我看了这个版本

void showOneByteBinaryNumber( char c ) {
    for ( int i = 1 << 7; i; i >>= 1 ) {
        c & i ? std::cout << 1 : std::cout << 0;
    }
}