【问题标题】:from a file convert binary to decimal从文件将二进制转换为十进制
【发布时间】:2020-06-28 17:49:04
【问题描述】:

大家好,我有一个问题。我有一个程序将二进制数转换为十进制数。但我想从文件转换二进制数。例如,在我的 txt 文件中是这样的二进制数: 10000111001 10001000100 100010110 100001000 00010010011 我想在我的程序中打开这个 txt 文件并将这个数字转换为十进制 我已经创建了类似的东西,但它没有保存我的输出

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

using namespace std;

int bin2dec(string binary)
{
    int decimal = strtol(binary.c_str(), NULL, 2);

    return decimal;
}

int main()
{
    string number;

    ifstream one("data.txt") //here are mine binary numbers
    ofstream two("second.txt") // i would like to save my converted numbers in this file
        while (!one.eof())
        {
            one >> number;
            number = bin2dec(number);
            two << number;

        }


    system("pause >nul");
    return 0;
}

【问题讨论】:

    标签: c++ binary


    【解决方案1】:

    您可以使用std::stoll 将二进制数据字符串转换为整数。一个基本的例子:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    void convbin(std::istream& is, std::ostream& os) {
        std::string bin;
        while(is >> bin) {        // extract word from "is"
            // Try to convert bin to a long long using base 2 (binary).
            // There's no error handling here and it may throw exceptions if it fails.
    
            os << std::stoll(bin, 0, 2) << '\n';
        }
    }
    
    int main() {
        std::ifstream one("data.txt");
        std::ofstream two("second.txt");
    
        if(one && two) convbin(one, two);
        else           std::cerr << "Error opening a file or both\n";
    }
    

    【讨论】:

    • 我现在知道了。但是如何将文件加载到这一行“std::istringstream one("10000111001 10001000100 100010110 100001000 00010010011");"我的意思是代替这些二进制数。他们会有一个文本文件
    • @Virozz 我已经更新了答案以使其更清晰。
    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2019-06-10
    • 2014-06-10
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多