0

次のデータを含む入力ファイルを取得しました

2
100
2
10 90
150
3
70 10 80

これで4行目(10 90)まで読めるようになりましたが、5行目(150)を読むとファイルポインタが4行目で止まってしまうようです。念のため infile.clear() を試しました。ファイル ポインタが正しく移動していること、または次の行に配置されていることを確認するにはどうすればよいですか? フィードバックをお待ちしております。

-アミット

#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;   

}
4

1 に答える 1

1

問題は、' '(スペース) を getline の「行末記号」として使用していることです。したがって、4 行目の数字を string に読み込むsと、最初の数字は に"10"なり、2 番目の数字"90\n150\n3\n70"は次のスペースまでのすべてになります。これはほとんど確実にあなたが望むものではなく、ファイルのどこにいるのか混乱する原因となります. 次に読む数字は 10 で、実際には 7 行目にいるのに、4 行目にいると思い込んでしまいます。

編集

これを修正する最も簡単な方法は、おそらくまったく使用せずgetline、入力から直接 int を読み取ることです。

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

これは改行を完全に無視するため、入力はすべて 1 行に表示されるか、行間でランダムに分割される可能性がありますが、読み取る数字の数を示す最初の数字があるので、それで問題ありません。

于 2013-02-15T01:05:25.640 に答える