std::stringstream
을 사용하여 지정된 형식으로 줄을 분리 할 수 있습니다.
std::string line; // A line of key/values from text
std::string key; // Temporary for our key
std::string value; // Temporary for our value
std::ifstream stream(path); // Load the file stream
std::stringstream splitter; // Prepare a stringstream as a splitter (splits on spaces) for reading key/values from a line
// Make sure we can read the stream
if (stream) {
// As long as there are lines of data, we read the file
while (std::getline(stream, line)) {
splitter << line; // Load line into splitter
splitter >> key; // Read the key back into temporary
splitter >> value; // Read the value back into temporary
splitter.clear(); // Clear for next line
variables[key] = value; // Store the key/value pair in our variable map.
}
}
else {
// The file was not found or locked, etc...
std::cout << "Unable to open file: " << path << std::endl;
}
이 <string>
및 <sstream>
을 포함해야합니다 예를 들면 다음과 같습니다이다. 나는 getline()
에 대해서도 <iostream>
가 필요하다고 생각합니다.
참고 : 나는 게시 할 수있는이 작업의 전체 예가 있지만 전체 연습을 마치겠다고 생각했습니다. 더 많은 정보가 필요하다면 알려주세요. 그러나 해결책을 찾지 않고 배우는 것이 가장 좋은 방법이라고 생각합니다. 로봇에 행운을 비네!
중요 : 내 솔루션은 접두사 공백 또는 '#'을 표현하지 못했습니다. 요구 사항을 변경하는 것이 좋을지 모르거나 약간 더 복잡한 구문 분석을 처리하기 위해 준비 지점으로 사용해야합니다. 예를 들어 키가 비어 있는지 확인할 수 있습니다. 그렇다면 변수 앞에 공백이 붙습니다. 그런 다음 키를 다시로드하고 마지막 변수 이름을 가져 오기 전에 공백을 추가하십시오. 마찬가지로 '#'키의 첫 번째 문자를 검사 할 수 있습니다. 조금 더 많은 일이지만, 예제 코드를 수정하여 수행 할 수 있어야합니다.
예를 들어 "C++ read file"에 대한 스택 오버플로를 검색하십시오. 지금까지 너무 많은 유사 콘텐츠가 있습니다. –
또한 이런 종류의 라이브러리에는 이미 많은 라이브러리가 있습니다 (예 : [libini] (http://sourceforge.net/projects/libini/)) - 휠을 다시 발명하는 것보다 더 나은 라이브러리를 사용하는 것이 좋습니다. –
대부분의 예제는 문자열 (텍스트 유형)에'std :: getline'과'std :: string'을 사용합니다. 당신은'fgets'을 사용하는 것으로 제한되어 있습니까? –