簡體   English   中英

從文件讀取數據

[英]Reading data from a file

我正在做一個練習,將坐標存儲到名為mydata的.txt文件中,然后從該文件中讀取回去。 但是,我在讀回書時遇到了麻煩。

碼:

#include "std_lib_facilities.h"

// Classes----------------------------------------------------------------------

struct Point{
Point(int a, int b):x(a), y(b) {};
Point(){};
int x;
int y;
};

// Main-------------------------------------------------------------------------

int main()
{
    vector<Point> original_points;
    vector<Point> processed_points;
    cout << "Please enter 7 coordinate pairs.\n";
    int x, y;
    while(cin >> x >> y){
              if(x == -1 || y == -1) break;
               original_points.push_back(Point(x, y));}
    cout << "Please enter file to send points to.\n";
    string name;
    cin >> name;
    ofstream ost(name.c_str());
    if(!ost)error("can't open output file", name);
    for(int i = 0; i < original_points.size(); ++i)
            ost << original_points[i].x << ',' << original_points[i].y << endl;
    ost.close();
    cout << "Please enter file to read points from.\n";
    string iname;
    cin >> iname;
    ifstream ist(iname.c_str());
    if(!ist)error("can't write from input file", name);
    while(ist >> x >> y) processed_points.push_back(Point(x, y));
    for(int i = 0; i < processed_points.size(); ++i)
            cout << processed_points[i].x << ',' << processed_points[i].y << endl;
    keep_window_open();
}

為了測試是否正在從文件中讀取數據,我將其推回到處理后的點向量中,但是當我運行程序並輸入點時,它不會從處理后的點向量中輸出任何點。 我認為問題出在...

while(ist >> x >> y)

這不是從文件讀取的正確方法。 任何幫助,將不勝感激,謝謝。

,您正在排隊

        ost << original_points[i].x << ',' << original_points[i].y << endl;

擋住了您的路,因為您沒有讀回來! 請使用空格代替該逗號,或者一定要讀回...

如果您不需要強制閱讀新行:

while( (ist >> x) && ist.ignore(1024,',') && (ist >> y))
    processed_points.push_back(Point(x, y));

最好的方法是先讀取整行,然后使用stringstream解析該點。

string temp;
while( std::getline(ist,temp) )
{
     std::stringstream line(temp);
     if( (line >> x) && line.ignore(1024,',') && ( line >> y ) )
         processed_points.push_back(Point(x, y));
}

代碼(ist >> x >> y)很好,除了逗號引起y的istream失敗。 該字符是逗號,而不是數字,因此轉換失敗。 亞歷克斯在這里是正確的軌道。

暫無
暫無

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

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