gpt4 book ai didi

c++ - 我如何将这些元素表达为 C++

转载 作者:行者123 更新时间:2023-11-28 05:11:38 26 4
gpt4 key购买 nike

您好,我想将其表达为 c++ vector< bitset<8>> s{ s1, s2,..., sn };n 是文件中元素的编号。所以,我让 cnt 来计算文件中的元素。所以,我做了这段代码。但我认为我的代码不对。但我不知道如何解决这个问题。

int cnt;
for (int x = 0; x < sizeof(files) / sizeof(files[0]); x++) {
std::ifstream f;

f.open(files[x].c_str(), std::ios::in);
if (f.good()) {
while (!f.eof()) {//end of file check
f >> str;
bitset<8> s(str);
cnt++;
str.clear();
}
f.close();
}

for (int i = 0; i < cnt; i++){
vector<bitset<8>> s{ s[i] };
}
}

最佳答案

您的代码可以简化很多。这是一个示例:

// Create the vector of bitsets. It is empty to start with.
vector<bitset<8>> s;

// Go through each file.
for (int x = 0; x < sizeof(files) / sizeof(files[0]); x++)
{
// Open the file.
// std::ifstream f(files[x].c_str()); // For pre C++11.
std::ifstream f(files[x]); // For C++11 or later.

// Define str here.
// It should not be needed outside the for loop.
std::string str;

// Keep reading from the file until read fails.
while (f >> str)
{
// Construct a bitset from the string.
bitset<8> si(str);

// Add the bitset to the vector of bitsets.
s.push_back(si);
}

// There is no need to explicitly close the file.
// The destructor will take care of that.
}

进一步阅读:Why is iostream::eof inside a loop condition considered wrong?

关于c++ - 我如何将这些元素表达为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43383818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com