在C ++中将分号分隔的文件中的整数分隔为不同的数字

Separate ints from a file separated by a semicolon into different digits in C++

我需要从文件中获取输入。此输入是任何长度的任何二进制数,其中数字由分号分隔,如下所示:

0; 1; 1; 0; 1; 0;

我要做的是将文件传递给一个变量,例如

if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        File = line;
    }
    myfile.close();
}

但我不确定要使变量 File 成为哪种数据类型。在此之后,我必须将数字存储在 arrayvector.

基本上,您要做的就是用分隔符拆分 string(在您的例子中,分隔符是 "; ")。它可以通过使用 std::string::find 方法来完成,我们查找 character/string 的 returns 索引,以及 std::string::substr 方法,根据提供的开始索引查找 returns 子字符串(来自 find)和要读取的字符数(我们只读取 01,因此长度始终为 1)。提取所需的子字符串后,您可以将其转换为适合您需要的数据类型。

下面是如何基于 string 创建 vector of bool 的简单示例:

#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string line = "0; 1; 1; 0; 1; 0; "; // In your case, 'line' will contain getline() result
    std::vector<bool> bits;
    std::size_t lastPos = 0;

    if(!line.empty()) bits.push_back(line.substr(0, 1) == "1");

    while((lastPos = line.find("; ", lastPos)) != std::string::npos)
    {
        lastPos += 2; // +2 because we don't want to read delimiter
        if(lastPos < line.size()) bits.push_back(line.substr(lastPos, 1) == "1");
    }

    for(auto bit : bits)
    {
        std::cout << bit << "\n";
    }
}

输出:

0
1
1
0
1
0

由于 任意长度 要求不适用(在评论中注意到),这是我的看法。这是一个 class 模板 (binreader<T>),其中 T 是您要从文件中提取的数字类型,例如 uint32_t(或 int32_t 用于签名值)。

binreader.hpp

#ifndef binreader_hpp_8ac51dd6_fe5f_11e8_a64e_90b11c0c0ff8
#define binreader_hpp_8ac51dd6_fe5f_11e8_a64e_90b11c0c0ff8

#include <iostream>
#include <string>
#include <climits>
#include <stdexcept>

// class template to read a line from a stream as a binary value and convert it
// to a user supplied type
template<typename T>
class binreader {
    T m_value; // the extracted value
public:
    // the number of bits in the type
    static constexpr size_t bits = sizeof(T)*CHAR_BIT;

    binreader() : m_value(0) {} // default constructor

    // input stream operator for reading a line
    friend std::istream& operator>>(std::istream& is, binreader& br) {
        std::string line;

        if(std::getline(is, line)) {
            T rv = 0; // the variable we'll populate with the extracted bits
            size_t bitcount=0; // overflow guard

            // loop through all characters in the line
            for(auto ch : line) {
                // just discard anything not '0' or '1'
                if(ch!='0' && ch!='1') continue;

                // check if we've already extracted the max number of bits
                if(++bitcount > bits)
                    throw std::overflow_error(
                        "Too many bits (>"+std::to_string(bits)+") for binreader type"
                    );

                // store the extracted bit
                rv <<= 1;       // shift up 1 step
                rv |= (ch-'0'); // OR the found 0 or 1
            }
            // a successful read, set the value of this binreader
            br.m_value = rv;
        } // else is.failbit will be set and the outer loop will stop
        return is;
    }

    // an output stream operator to print a binreader value
    friend std::ostream& operator<<(std::ostream& os, const binreader& br) {
        os << br.m_value;
        return os;
    }

    // conversion to T for convenience
    operator T () const { return m_value; }
};

#endif

用法示例:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "binreader.hpp"

// a test function template to open a file, extract and store the values
// in a std::vector<T> that will be returned to the caller

template<typename T>
std::vector<T> trytype(const std::string& filename) {
    std::vector<T> rv;

    // open file
    std::ifstream fi(filename);

    if(fi) { // opened successfully?
        // declare a binreader variable of a wanted type
        // suitable to fit the binary numbers in the file
        binreader<T> value;

        std::cout << "Reading at most " << value.bits << " bits\n";
        try {
            // extract the value on one line
            while(fi >> value) {
                // store the value to return using the
                // conversion operator T ()
                rv.push_back(value);
            }
        } catch(const std::exception& ex) {
            std::clog << " ERROR: " << ex.what() << "\n";
        }
    }
    return rv;
}

// function template to display values in a container
// (a std::vector<T> that is returned from trytype<T>)
template<typename C>
void display(const C& extracted_values) {
    std::cout << " Extracted values:\n";
    for(auto v : extracted_values) {
        std::cout << " " << v << "\n";
    }
}

int main(int argc, char* argv[]) {
    // make a vector of all the command line arguments
    std::vector<std::string> args(argv+1, argv+argc);

    // open all files given as command line arguments and
    // try to extract binary values using different types
    // and call display() to print the values
    for(const auto& file : args) {
        display( trytype<uint64_t>(file) );
        display( trytype<int64_t>(file) );
        display( trytype<uint32_t>(file) );
        display( trytype<int32_t>(file) );
        display( trytype<uint16_t>(file) );
        display( trytype<int16_t>(file) );
        display( trytype<uint8_t>(file) );
        display( trytype<int8_t>(file) );
    }
}

示例文件:

0; 1; 1; 0;
1; 1; 1; 0; 1; 0; 1; 1;
1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1;
1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1;
1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1; 1; 1; 1; 0; 1; 0; 1; 1;

示例输出:

Reading at most 64 bits
 Extracted values:
 6
 235
 60395
 3958107115
 16999940616948018155
Reading at most 64 bits
 Extracted values:
 6
 235
 60395
 3958107115
 -1446803456761533461
Reading at most 32 bits
 ERROR: Too many bits (>32) for binreader type
 Extracted values:
 6
 235
 60395
 3958107115
Reading at most 32 bits
 ERROR: Too many bits (>32) for binreader type
 Extracted values:
 6
 235
 60395
 -336860181
Reading at most 16 bits
 ERROR: Too many bits (>16) for binreader type
 Extracted values:
 6
 235
 60395
Reading at most 16 bits
 ERROR: Too many bits (>16) for binreader type
 Extracted values:
 6
 235
 -5141
Reading at most 8 bits
 ERROR: Too many bits (>8) for binreader type
 Extracted values:

 ▒
Reading at most 8 bits
 ERROR: Too many bits (>8) for binreader type
 Extracted values:

 ▒

请注意,8 位类型将打印字符而不是数字,但它们对算术运算同样有效。 static_cast 到更大的类型以显示它们的值。