2017-01-26 1 views
0

그래서 입력 파일의 모든 행에서 특정 부분을 가져 오려고합니다. 지금까지이 있어요 : 나는 (line.substr(line.find("VAR_CAL_PATH2=") + 1)) 부분은 "경로 1 ="후 그리고 경로 1에 넣어 것입니다 무엇이든 취할 것 이해 것에서입력 파일에서 변수 추출 및 설정 C++

ifstream fin("text.txt"); 
string line; 
while (getline(fin, line)) { 
    if (line.find("Set") == 0) 

    { 

     istringstream sin1(line.substr(line.find("path1=") + 1)); 
     sin1 >> path1; 
     istringstream sin2(line.substr(line.find("path2=") + 1)); 
     sin2 >> path2; 

    } 

} 

을, 나는 그것을 잘못있어 같아요. 내 입력 파일은 두 줄이 있습니다

Set path1="somepath" 
Set path2="someotherpath" 

while 루프 내가 얻을 종료

경로 1

을 = "설정"및 경로 2 = "someotherpath"하지만 내가 원하는 경로 1 = "somepath는"및 경로 2 = "someotherpath"입니다
+1

당신은 모든 라인의 경로 1과 경로 2 모두를 업데이트 문제를 일으킨다. –

답변

0
  1. find() 문자열의 시작 위치를 반환합니다.
  2. path2 값을 구문 분석 할 때 path1 값을 덮어 씁니다.

이러한 수정과 코드 :

const string path1field = "path1="; 
const string path2field = "path2="; 

string path1 = "", path2 = ""; 

ifstream fin("text.txt"); 
string line; 

while (getline(fin, line)) 
{ 
    if (line.find("Set") != string::npos) 
    { 
     size_t path1pos = line.find(path1field); 
     size_t path2pos = line.find(path2field); 

     if (path1pos != string::npos) 
     { 
      istringstream sin1(line.substr(path1pos + path1field.length())); 
      sin1 >> path1; 
     } 

     if (path2pos != string::npos) 
     { 
      istringstream sin2(line.substr(path2pos + path2field.length())); 
      sin2 >> path2; 
     } 
    } 
} 

cout << "path1: " << path1 << endl; 
cout << "path2: " << path2 << endl; 
+0

고마워요! 그게 해결! :) –

0

find() 함수는 std::string의 문자열 시작 위치를 반환합니다. 1을 추가하면 검색 한 문자열 다음의 위치가 아니라 시작 위치 + 1을 가리 킵니다. @ Jordfräs가 말한대로

사용할 수있는 표준 라이브러리의 좋은 문서, 예를 들어, 많이있다, http://en.cppreference.com/w/cpp/string/basic_string/find

0

문자열 변수에 대한 또 다른 (일반적인) 솔루션이 될 수 :

ifstream fin("text.txt"); 
string line; 

const vector<string> pathsNames={"path1=", "path2="}; 

vector<string> paths(pathsNames.size()); 

while (getline(fin, line)) { 
    if (line.find("Set") == 0) 

    { 
     for(std::vector<string>::size_type x=0; x<pathsNames.size(); x++){ 
      if(line.find(pathsNames[x])!=string::npos){ 
       paths[x]=line.substr(line.find(pathsNames[x]) + pathsNames[x].length()); 
       break; 
      } 
     } 
    } 

} 
//print results 
for(std::vector<string>::size_type x=0; x<pathsNames.size(); x++){ 
    cout << pathsNames[x] << paths[x] << endl; 
} 
관련 문제