簡體   English   中英

從文件讀取數據,輸入文件名

[英]reading data from files, file name as input

我正在編寫一個程序,該程序從作為輸入字符串給出的不同文件中讀取數據,並將其存儲到向量的向量中。 我無法調試讀取不同文件的循環的問題。 我已經關閉了ifstream對象,使用空函數清除了字符串...但是當我輸入第二個文件名時,它仍然會終止。

我正在復制代碼供您細閱。 這是另一個函數調用的函數。 轉位器轉置矩陣。

碼:

vector<vector<float> > store1,store2;
ifstream bb;

string my_string;

float carrier;
vector<float> buffer;

cout<<"enter the file name"<<endl;
getline(cin,my_string);

while (my_string!="end")
{

    bb.open(my_string.c_str());
    while (!bb.eof())
    {
        bb >> carrier;

        if (bb.peek() == '\n' || bb.eof() )
        {
            buffer.push_back(carrier);
            store1.push_back(buffer);
            buffer.clear();
        }

        else
        {
            buffer.push_back(carrier);
        }


    }

    bb.close();
    buffer.clear();
    transposectr1(store1);
    storex.push_back(store1[1]);
    storey.push_back(store1[0]);
    store1.clear();
    my_string.empty();
    cout<<"done reading the file"<<endl;
    cout<<"enter the file name"<<endl;
    getline(cin,my_string);
}

我真的不清楚您要做什么。 但是在使用istream時,我有一個黃金法則:

切勿使用eof()函數!

它幾乎可以肯定不會按照您的想法去做。 相反,您應該測試讀取操作是否成功。

int x;

while( in >> x ) {
   // I read something successfully
}

您可能還希望避免使用peek()。 請牢記此建議,重新編寫代碼。

bb.clear();

在bb.close()之后,您可能會得到正確的東西。 bb.close()不會重置我認為的光標。

尼爾·巴特沃思(Neil Butterworth)是對的

切勿使用eof()函數!

此鏈接說明了原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM