2012-03-09 2 views
0

일부 데이터가 포함 된 텍스트 파일이 있는데이 파일을 내 개체로 읽으려고합니다.다른 문자로 구분 된 C++ 값으로 텍스트 파일 읽기

그런 다음 파일 이름으로 구성된 아주 간단한 형식, 치수 값 한 쌍의 값 쌍의 목록입니다 : 예를 들어

StringFileName 
IntWidth IntHeight 
IntA:IntB IntA:IntB IntA:IntB 
IntA:IntB IntA:IntB IntA:IntB 
IntA:IntB IntA:IntB IntA:IntB 

: 여기

MyFile.txt 
3 3 
1:2 3:4 4:5 
9:2 1:5 2:1 
1:5 8:3 4:2 
There may be more unrelated text here 

내가 너무 가지고 무엇을 지금까지이 같은

void OnLoad(char* InputFilename) { 
    string Filename; 
    int Width; 
    int Height; 

    // open the file 
    ifstream inputFile(InputFilename); 

    // get the filename 
    getline(inputFile, Filename); 
    cout << "Filename is " << Filename << endl; 

    // get the width and height 
    string dataLine; 
    getline(inputFile, dataLine); 
    stringstream ss(dataLine); 
    ss >> Width; 
    ss >> Height; 
    cout << "Dimensions are " << Width << "x" << Height << endl; 

    // get the lines of tile-data 
    for (int Y = 0; Y < Height; Y++) { 
     /* 
     * Here is where I'm getting stuck. 
     * I have a string of "i:i i:i i:i" values, and I get a series of strings 
     * of "i:i" values, but can't work out the neatest way of splitting it out. 
     */ 
     getline(inputFile, dataLine); 
     stringstream row(dataLine); 
     for (int X = 0; X < Width; X++) { 
      int IntA; 
      int IntB; 
      // ? 
      DoStuffWith(IntA, IntB); 
     } 

    } 
} 
+0

std :: cin >> IntA >> ":">> IntB; – Spidey

+0

그게 작동하지 않습니다, 당신은 const char * – 111111

+0

내가 그들을 섞을 수 없다, 내가 변환 오류가 스트림으로 수 없습니다. 'valPair >> IntA >> ":">> IntB;' '오류 C2678 : 바이너리'>> ':'std :: basic_istream <_Elem, _Traits> '유형의 왼쪽 피연산자를 취하는 연산자가 없습니다. – Cylindric

답변

2

뭔가

작동합니다
std::ifstream file("filename"); 
std::string file_name; 
int height, width; 
file >> file_name >> height >> width; 
// i don't know what your format is but it isn't very importance 
std::deque<std::pair<int, int> > pairs; 
std::string line; 
int i, j; 
char a; 
while(std::cin >> i >> a >> j) //here i j are values in your pair. 
{ 
    if(a!=':') break; 
    pairs.push_back(std::make_pair(i, j)); 
} 
+0

사실 그것은 STL로 돌아가는 C++의 더 많은 방법입니다! 이것은 열 구분자가 아니라면 실제로 작동 할 것입니다 ... – xtofl

+0

글쎄, 내가 필요로하는 것이 무엇인지 알지 못했는데, 이상적으로 스트림 연산자로 구조체의 일종이있을 것입니다. – 111111

+0

@xtofl 이것은 분리 기호 BTW를 처리하지만 더 좋을 것입니다. – 111111

2

부스트의 분할 기능을 임의로 많은 술어에 나눌 수 있습니다 strtok를. 따라서 다음과 같이 할 수 있습니다.

vector<string> results; 
boost::split(results, data_string, boost::is_any_of(" :")); <- splits on spaces and ":" 

다음은 모든 데이터를 편리한 용기에 담았습니다!

귀하의 경우에는 최선의 해결책이 아닐 수도 있지만 유의해야합니다.

0

이제 "* i"를 사용하여 더 깔끔하게 얻을 수있는 int 값을 할당 할 수 있습니다.

std::string line; 
      do{ 
       getline(inputFile,line); 
       sregex_token_iterator end; 

       for(sregex_token_iterator i(line.begin(), line.end(), pattern,-1); i!=end;++i) 
       { 
        cout<< *i << " " ; 
       } 
      }while(!inputFile.eof()); 
+0

죄송 합니다만 이미 답변을 수락했음을 알지 못해 죄송합니다. – Ajai

+0

감사합니다. 나중에 참조 할 수 있도록 다른 옵션을 사용하는 것이 좋습니다. – Cylindric

관련 문제