2014-04-14 7 views
0

내가 파일 내용이 될 글로벌 2D 벡터 '매트릭스 에 텍스트 파일에서 데이터를 읽기 위해 노력하고 C를 사용하여 2D 벡터에 저장 같은 :는 텍스트 파일에서 데이터를 읽고 ++ 언어

8 3

1, 6, 2

9 2,5-

1, 5, 25

7, 4, 25

내 실수는 무엇인지 알 수 없었습니다. 내 코드 저장소 첫 번째 행.

#include <iostream> 
#include<fstream> 
#include<algorithm> 
#include<vector> 
#include <sstream> 
#define EXIT_FILE_ERROR (1) 
#define EXIT_UNEXPECTED_EOF (2) 
#define EXIT_INVALID_FIRSTLINE (3) 
#define MAXLINE (10000) 

std::vector< std::vector<int> > matrix; 
int main(int argc, const char * argv[]) 
{ 
    FILE *fp; 

    std::string sFileName = "Matrix1.txt"; 
    std::ifstream fileStream(sFileName); 
    if (!fileStream.is_open()) 
    { 
     std::cout << "Exiting unable to open file" << std::endl; 
     exit(EXIT_FILE_ERROR); 
    } 

    std::string line; 

    while (getline (fileStream,line)) 
    { 
     std::stringstream ss(line); 
     std::vector<int> numbers; 
     std::string v; 
     int value; 
     while(ss >> value) 
     { 
      numbers.push_back(value); 
      std::cout << value << std::endl; 
     } 
     matrix.push_back(numbers); 
    } 

    fileStream.close(); 

    if ((fp = fopen(sFileName.c_str(), "r")) == NULL) 
    { 
     std::cout << "Exiting unable to open file" << std::endl; 
     exit(EXIT_FILE_ERROR); 
    } 
    return 0; 
} 

내 실수는 무엇인가요? 다음 코드 조각 코드에서

+0

아마도 그 쉼표로 인해 구문 분석이 엉망이 될 수 있습니다. –

+0

그 외에도 FILE * 및 ifstream을 왜 혼합하고 있습니까? Btw,'std :: string v;'는 사용되지 않습니다. 또한 항상 출력물을 공유하고보고 싶은 내용을 공유하십시오. – lpapp

+0

Noooooo !!!! 제발, 다른 파일 구문 분석 질문. StackOverflow에서 "C++ read file parse 2d"를 검색하십시오. –

답변

0

변경을 두 번 while 루프 : 실패의

while(getline(fileStream, line, '\n')) { 
     std::stringstream ss(line); 
     std::vector<int> numbers; 
     std::string in_line; 
     while(getline (ss, in_line, ',')) { 
      numbers.push_back(std::stoi(in_line, 0)); 
     } 
     matrix.push_back(numbers); 
    } 

이유 : 당신은 ss 스트림의 구문 분석과 함께 일을 엉망으로, 당신은 구분 기호를 도입 할 필요가있다.

그러나 이러한 종류의 구문 분석은 권장하지 않습니다. C++ 11은 구문 분석을 원활하게 해주는 regular expressions을 지원합니다.

관련 문제