getline的文件指针移动

时间:2013-02-15 00:56:47

标签: c++ getline

我有一个包含以下数据的输入文件

2
100
2
10 90
150
3
70 10 80

现在,我能够读到第4行(10 90)但是当读取第5行(150)时,文件指针似乎卡在第4行。我试过infile.clear()只是因为。如何确保文件指针正确移动或将其放在下一行?感谢您的反馈。

-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 个答案:

答案 0 :(得分:1)

问题是你使用' '(空格)作为getline的“行终止符”。因此,当您将第4行的数字读入字符串s时,第一个将是"10",第二个将是"90\n150\n3\n70" - 也就是说,所有内容都将在下一个空间。这几乎不是你想要的,并且导致你对文件中的位置感到困惑。你读的下一个号码将是10,导致你认为你在第4行,而实际上你在第7行。

修改

解决此问题的最简单方法可能是根本不使用getline,只需直接从输入中读取内容:

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

这完全忽略了换行符,所以输入也可能全部在一行上或者在行之间随机分割,但是因为你有一个初始数字告诉你要读多少个数字,那就没关系了。