2016-03-04 174 views
-1

我想讀取一個數字文件。isstringstream從文件讀取C++

使用我的代碼,我只讀了每行的第一個數字。 getline()獲取該行,但是isstringstream只讀取該行中的1個數字而忽略其餘數字。我需要閱讀每一個號碼,將其插入我的矢量

文件的例子是:

118 115 115 116 116 116 118 117 115 114 114 115 117 118 117 114 114 116 117 
116 117 117 117 116 115 115 115 115 116 118 118 117 116 114 112 112 112 114 
115 ... so on 

int main() 
{ 
vector<unsigned char>gray; 
int lines=2; 

    for (int i = 0; i < lines; i++) 

    { 
     string line4; 
     getline(infile, line4); 
     istringstream iss4(line4); 
     int g; 
     iss4 >> g; 

     gray.push_back((unsigned char)g); 
    } 
return 0; 
} 
+3

因此,編寫一個代碼來做到這一點。兩個循環並不多。 – LogicStuff

+0

爲什麼連兩個循環?剛剛閱讀每個值使用'infile >>' – NathanOliver

+0

@NathanOliver OP是計數行只讀前兩個。然後,我的意思是總共兩個循環 – LogicStuff

回答

0

改變你的代碼位:

#include <cstdint> // For uint8_t 

int main() 
{ 
    vector<uint8_t>gray; 
    unsigned int line_number = 0U; 
    std::string text; 
    while (getline(infile, text)) 
    { 
     istringstream iss4(text); 
     uint8_t value; 
     while (iss4 >> value) 
     { 
      gray.push_back(value); 
     } 
    } 
return 0; 
} 

注:

  1. 當提取比一個值更多的 時,istringstream可以像文件一樣對待。
  2. uint8_t類型保證8位無符號整數。
0

您可以使用std::istream_iterator方法;這裏用std::cin舉例說明。

#include <algorithm> 
#include <iostream> 
#include <iterator> 
#include <vector> 

int main() 
{ 
    std::vector<unsigned char> gray; 

    std::copy(std::istream_iterator<int>{std::cin}, 
       std::istream_iterator<int>{}, 
       std::back_inserter(gray)); 

    return 0; 
}