2011-08-04 70 views
3

昨天我做了一個小腳本,有一些幫助來閱讀.csv文件。儘管我發現了一種讀取第一個值並將其存儲的方法,但由於某種原因,它存儲了最後一個值。讀取.csv文件中字段的值?

我存儲了我認爲應該是value1下的第一個值,並重新顯示它以確保它正確顯示並且事實上存儲在可調用變量下。

有沒有人知道這段代碼有什麼問題?我想我應該使用矢量,但是當我閱讀我在互聯網上發現的關於它們的參考表時,我正在引起一些注意。任何幫助表示讚賞。

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main() 
{ 

    int loop = 1; 
    string value; 
    string value1; 

    while(loop = 1) 
    { 

     cout << "Welcome! \n" << endl; 

     ifstream myfile; 

     myfile.open ("C:/Documents and Settings/RHatfield/My Documents/C++/Product Catalog Creator/Source/External/Sample.csv"); 

     while (myfile.good()) 

     getline (myfile, value, ','); 
     cout << string (value) << endl; 

     value1 = value; 

     cout << value1; 

     myfile.close(); 

     system("PAUSE"); 

     return 0; 
    } 


} 
+0

重複以下問題:http://stackoverflow.com/questions/1120140/csv-parser-in-c –

回答

1

您的錯誤似乎是純代碼格式。

while (myfile.good()) 

循環後沒有{}。所以只有下一行重複。

下面的代碼在讀完整個文件後執行。

cout << string (value) << endl; 

因此value存儲文件的最後一行。

+0

是的你的權利,但是當我修復它,它做同樣的事情,只列出所有的逐個值,然後存儲最後一個並重新列出它。有誰知道我在哪裏可以找到很好的參考資料,因爲現在我對結果更加困惑。感謝您的幫助,只是在我面前學習了很多東西。 – Rob

+0

@Rob,現在它是純粹的算法問題。有很多解決方案。如果你只想得到第一行,你不需要任何循環。只要用'if'語句替換'while'即可。 –

+0

你是對的,但不是說我想從行(某些數字)和列(某個數字)抽取數據,我該怎麼做,甚至只是說讀線(某個數字)並返回所有值。我不能只是再次改變while循環。這是矢量進來嗎? – Rob

0

你可能想改變你while循環條件:

char separator; 
int value1; 
int value2; 
int value3; 
while (myfile >> value1) 
{ 
    // Skip the separator, e.g. comma (',') 
    myfile >> separator; 

    // Read in next value. 
    myfile >> value2; 

    // Skip the separator, e.g. comma (',') 
    myfile >> separator; 

    // Read in next value. 
    myfile >> value3; 

    // Ignore the newline, as it is still in the buffer. 
    myfile.ignore(10000, '\n'); 

    // Process or store values. 
} 

上面的代碼片段並不十分可靠,但展現了從文件中讀取,跳過非數字分離器和處理結束的概念該線。代碼也被優化。