2009-07-25 6 views
0

좌표를 mydata라는 .txt 파일에 저장하고 해당 파일에서 다시 읽는 연습을하고 있습니다. 그러나, 나는 "문제가 다시 읽기를 가진파일에서 데이터 읽기

코드 M :.

#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(); 
} 

는, 데이터가 내가 처리 된 점 벡터로 다시 밀어하고있는 파일에서 읽을되고 있는지 테스트하기 만하면 나는 프로그램을 실행하고 포인트를 입력, 그것은. 나는 문제가에있는 processed_points 벡터에서 출력하지 점을 생각 하는가 ...

while(ist >> x >> y) 

하고이 파일에서 읽을 수있는 올바른 방법이 아니다 어떤 도움을 주셔서 감사합니다, 감사합니다.

답변

3

, 당신이 그것을 다시 읽어 NOT하고 있기 때문에 당신이

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

가장 좋은 방법은 첫 번째 전체 라인을 읽는 것입니다 : 어느

1

하는 새로운 라인을 읽는 강제 할 필요가없는 경우 ... 다시 읽어 마십시오, 해당 쉼표의 공간을 사용하거나 , 그리고 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)); 
} 
0

코드 (ist >> x >> y)는 괜찮습니다. 단, 쉼표로 인해 istream이 실패하게됩니다. 문자는 쉼표이며 숫자가 아니므로 변환에 실패합니다. 알렉스는 여기서 옳은 길을 걷고 있습니다.