2017-04-13 41 views
0

嗨我想表達這個成C++向量<位集< 8 >> s {s1,s2,...,sn}; n是文件中元素的編號。所以,我讓cnt來計算文件中的元素。 所以,我做了這個代碼。但我認爲我的代碼是不正確的。但我不知道如何解決這個問題。我怎麼能表達這個元素到c + +

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] }; 
    } 
} 
+2

參見[?爲什麼是的iostream :: EOF算錯了一個循環條件中(http://stackoverflow.com/questions/5605125/why-is -iostreameof-loop-condition-considered-wrong) –

+0

[從文件中讀取字符串並將其轉換爲bitset <12>](http://stackoverflow.com/questions/43381239/read-string-from-file -and-turn-into-bitset12) – chbchb55

+1

你最後一個for循環並沒有做任何有用的事情。 – chbchb55

回答

1

您的代碼可以簡化很多。這裏有一個例子:

// 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?

+2

Ant for'loop'可能會進一步簡化爲'for const auto&file:files)':) –