2013-02-15 134 views
0

我有一個輸入文件具有以下數據文件指針移動的函數getline

2 
100 
2 
10 90 
150 
3 
70 10 80 

現在,我能讀,直至4號線(10 90),但讀5日線(150)時,文件指針似乎被困在第四線。我已經嘗試infile.clear()只是incase。如何確保文件指針正確移動或將其放在下一行?感謝您的反饋。

-Amit

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

using namespace std; 

int main(void) { 

int cases; 
int total_credit=0; 
int list_size=0; 
string list_price; 


//Read file "filename". 

ifstream infile; 
infile.open("A-large-practice.in",ifstream::in); 
if(!infile.is_open()) { 
    cout << "\n The file cannot be opened" << endl; 
    return 1; 
} 

else { 
    cout<<"Reading from the file"<<endl; 
    infile >> cases;  
    cout << "Total Cases = " << cases << endl; 
    int j=0; 

    while (infile.good() && j < cases) { 

     total_credit=0; 
     list_size=0; 

     infile >> total_credit; 
     infile >> list_size; 

     cout << "Total Credit = " << total_credit << endl; 
     cout << "List Size = " << list_size << endl; 
     //cout << "Sum of total_credit and list_size" << sum_test << endl; 

     int array[list_size]; 
     int i =0; 
     while(i < list_size) { 
      istringstream stream1; 
      string s; 
      getline(infile,s,' '); 
      stream1.str(s); 
      stream1 >> array[i]; 
      //cout << "Here's what in file = " << s <<endl; 
      //array[i]=s; 
      i++; 
     } 

     cout << "List Price = " << array[0] << " Next = " << array[1] << endl;   
     int sum = array[0] + array[1]; 
     cout << "Sum Total = " << sum << endl; 
     cout <<"Testing" << endl; 
     j++;  
    }  
} 
return 0; 

} 

回答

1

的問題是,你使用' '(空間)作爲你的 「行終止」 的函數getline。所以當你將第4行的數字讀入字符串s時,第一個數字是"10",第二個數字是"90\n150\n3\n70" - 也就是說,到下一個空間的所有數據。這幾乎不是你想要的,而是導致你對文件中你的位置感到困惑。你看了會10下一個號碼,導致你認爲你是在第4行的時候,其實你是第7行

編輯

解決這個問題的最簡單的方法可能是不使用getline可言,只是直接從輸入讀取整數:

while (i < list_size) 
    infile >> array[i++]; 

這忽略共新行,所以輸入可能會成爲所有在同一行或行之間的分裂隨機,但你有一個初步的數它告訴你要讀多少個數字,這很好。

+0

你是對的Chris。我明白你的意思了。我想知道是否有一種方法可以避免它,否則我正在考慮使用矢量來解析包含數字列表的字符串行。 – Amit 2013-02-15 03:38:11