2013-11-02 2 views
0

substr 함수를 사용하여 첫 번째 열 값 (name, name2 및 name3)을 읽는 방법은 무엇입니까?for 루프를 사용하여 특정 문자까지 읽을

name;adress;item;others; 
name2;adress;item;others; 
name3;adress;item;others; 

나는

이 같이
cout << "Read data.." << endl; 
    if (dataFile.is_open()) { 
     i=-1; 
     while (dataFile.good()) { 
      getline (dataFile, line); 
      if (i>=0) patient[i] = line; 
      i++; 
     } 
     dataFile.close(); 
    } 

답변

0
#include <string> 
#include <iostream> 
#include <fstream> 
#include <vector> 

int main() 
{ 
    std::fstream f("file.txt"); 
    if(f) 
    { 
     std::string line; 
     std::vector<std::string> names; 
     while(std::getline(f, line)) 
     { 
      size_t pos = line.find(';'); 
      if(pos != std::string::npos) 
      { 
       names.push_back(line.substr(0, pos)); 
      } 
     } 

     for(size_t i = 0; i < names.size(); ++i) 
     { 
      std::cout << names[i] << "\n"; 
     } 
    } 

    return 0; 
} 
0

를 작성했습니다

첫 번째 ';'의 위치를 ​​찾은 다음 그 0에서 substr를 취할 필요가
int pos = s.find(';'); 
if (pos == string::npos) ... // Do something here - ';' is not found 
string res = s.substr(0, pos); 

위치. 다음은 demo on ideone입니다. 첫 번째 세미콜론 읽기 전에

+0

모든 라인 1을 읽어? 왜 새 줄을 잡지 않고 첫 번째 줄을 선택합니까? –

+0

@BernardoBaalen 그 속도가 느립니다. 또한'getline'은 모든 개행 문자를 제거합니다. – dasblinkenlight

0

당신은 콘텐츠를 다음 줄의 나머지 부분을 무시할 수 있습니다 :

std::vector<std::string> patient; 

std::string line; 
while (std::getline(file, line, ';')) 
{ 
    patient.push_back(line); 
    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
} 
관련 문제