2013-02-23 66 views
0

我是從一個文件中讀取數據:如何使用任何流上的wstring使用<code>wifstream</code></p> <p>txt文件看起來像這樣來提取數據

1,2,3,4,5,6,7 
2,3,4,5,6,7,8 
... 
... 

,每個數字都是我需要爲我的節目的ID和逗號分隔 這裏是我的代碼

wifstream inputFile(FILE_PATH); 
if(inputFile) 
{ 
    wchar_t regex; 
    int id; 
    while(inputFile) 
    { 
     inputFile>>id; 
     inputFile.get(regex); 

     cout << id << ", ";       
    } 
    inputFile.close(); 
} 

此代碼工作完全正常,直到我改變,其中單條線一次讀的閱讀計劃,我想在線上做類似的事情,這樣我就可以從行中讀取數據,而流的緩衝區一旦像上面一樣讀取數據就會彈出數據。但我無法得到它的工作。 這裏是我的代碼

wifstream inputFile(FILE_PATH); 
    wstring line; 
    if(inputFile) 
    { 
     while(!inputFile.eof()) 
     { 

      std::getline(inputFile, line); 

      for(int i=0; i<line.length(); i+=2) 
      { 
       int id; 
       wchar_t regex; 
       wstringstream(line)>>id; // doesn't work as it keep getting the same number 
       wstringstream(line).get(regex); 

       cout << id << ", "; 
      } 
      cout << endl; 

     } 
     inputFile.close(); 
    } 

我認爲它不工作的原因是,我不使用流得當,它保持了最初的索引讀取ID和永遠不會進步,無論多少次我用>>(反正可能不是正確的方法),我也試過wifstream,也沒用。

我該如何解決這個問題?

回答

1

您每次使用時都重新創建wstringstream。將創建移到循環外部:

wifstream inputFile(FILE_PATH); 
wstring line; 
if(inputFile) 
{ 
    while(!inputFile.eof()) 
    { 

     std::getline(inputFile, line); 

     wstringstream istring(line); 
     for(int i=0; i<line.length(); i+=2) 
     { 
      int id; 
      wchar_t regex; 
      istring>>id; 
      istring.get(regex); 

      cout << id << ", "; 
     } 
     cout << endl; 

    } 
    inputFile.close(); 
} 
+0

OMG就是這樣一個愚蠢的錯誤!謝謝! – ryf9059 2013-02-23 15:39:48

相關問題