2015-01-13 7 views
-1

내 로봇 공학 팀에게 변수 값을 텍스트 파일에 저장하여 코드를 업데이트하지 않고도 값을 업데이트 할 수있는 기능을 작성해야했습니다. 예 : 휠 속도를 높이십시오. 우리가 결정한 형식은 다음과 같습니다. 공백 또는 #, 변수 이름, 공백, 변수 값.텍스트 파일에서 변수 읽기 C++

variable1 1 
#variable3 4 
setspeed 10 

변수로 필요한 변수는 첫 번째 열에서 검색하여 반환하는 것입니다. 내가 fgets를 사용하여 줄 단위로 읽을 것을 권장했지만, 나는 우리 형식을 사용하여 어떻게 줄을 끊을 것인지 확신 할 수 없다.

+3

예를 들어 "C++ read file"에 대한 스택 오버플로를 검색하십시오. 지금까지 너무 많은 유사 콘텐츠가 있습니다. –

+0

또한 이런 종류의 라이브러리에는 이미 많은 라이브러리가 있습니다 (예 : [libini] (http://sourceforge.net/projects/libini/)) - 휠을 다시 발명하는 것보다 더 나은 라이브러리를 사용하는 것이 좋습니다. –

+0

대부분의 예제는 문자열 (텍스트 유형)에'std :: getline'과'std :: string'을 사용합니다. 당신은'fgets'을 사용하는 것으로 제한되어 있습니까? –

답변

0

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>가 필요하다고 생각합니다.

참고 : 나는 게시 할 수있는이 작업의 전체 예가 있지만 전체 연습을 마치겠다고 생각했습니다. 더 많은 정보가 필요하다면 알려주세요. 그러나 해결책을 찾지 않고 배우는 것이 가장 좋은 방법이라고 생각합니다. 로봇에 행운을 비네!

중요 : 내 솔루션은 접두사 공백 또는 '#'을 표현하지 못했습니다. 요구 사항을 변경하는 것이 좋을지 모르거나 약간 더 복잡한 구문 분석을 처리하기 위해 준비 지점으로 사용해야합니다. 예를 들어 키가 비어 있는지 확인할 수 있습니다. 그렇다면 변수 앞에 공백이 붙습니다. 그런 다음 키를 다시로드하고 마지막 변수 이름을 가져 오기 전에 공백을 추가하십시오. 마찬가지로 '#'키의 첫 번째 문자를 검사 할 수 있습니다. 조금 더 많은 일이지만, 예제 코드를 수정하여 수행 할 수 있어야합니다.

0
//---------------------------------------------------------------------------- 
#include <iostream> 
#include <sstream> 
#include <fstream> 
//---------------------------------------------------------------------------- 
class Entry 
{ 
public: 
    Entry():name("\0"), value(0.0){} 
    //Entry (std::string _name, double _value): name(_name), value(_value){} 
    ~Entry() {} 

    friend std::ostream& operator<<(std::ostream& os, const Entry& entry); 
    friend std::istream& operator>> (std::istream& is, Entry& entry); 

    std::string GetName() {return name;} 
    double GetValue() {return value;} 

private: 
    std::string name; 
    double value; 
} ; 

std::istream& operator>> (std::istream& is, Entry& entry) 
{ 
    is >> entry.name >> entry.value; 
    return is; 
} 

std::ostream& operator<<(std::ostream& os, const Entry& entry) 
{ 
    os << entry.name << " = " << entry.value << "\n"; 
    return os; 
} 

//---------------------------------------------------------------------------- 
int main() 
{ 
     std::string filename = "test.txt"; 
     std::ifstream ifs (filename); 

     if (ifs.is_open()) 
     { 
      std::cout << "Variable name:\t"; 
      std::string name; 
      std::getline(std::cin, name); 
      Entry entry; 
      bool found = false; 

      while (ifs >> entry) 
       if (entry.GetName() == name) 
       { 
        found = true; 
        std::cout << entry; 
        break; 
       } 

      if (!found) 
       std::cout << "The name is wrong\n"; 

      ifs.close(); 
     } 
     else 
      std::cout << "Error opening file "<< filename; 

     std::cin.sync(); 
     std::cin.get(); 
     return 0; 
} 
//----------------------------------------------------------------------------- 

저는 변수 이름을 공백으로 시작하는 것이 좋습니다. 필요하다면 차이를 만들기 위해 "%"와 "#"를 제안합니다.