title: How to replace a string with another string in csv file using C++
body: <p>I am opening a csv file which contains entries in the form "key,value".
  Task is to find a particular key and modify its corresponding value with another string. (key &amp; value : both are strings).</p>
  
  <pre><code>int main() 
  
  {   
  
      std::fstream m_file;
      m_file.open("input.csv", std::ios::in | std::ios::out);
      m_file &lt;&lt; "Star,Treks\n";
      m_file &lt;&lt; "Captain,America\n";
      m_file &lt;&lt; "Black,Cats\n";   
      m_file &lt;&lt; "Ninja,Fighters\n";
  
      std::string row;
      std::string key = "Black";
      std::string value = "Dreamers";
      while (std::getline(m_file, row)) {
          std::size_t pos = row.find(',');
          std::string retrieved_key = row.substr(0, pos);
          std::string retrieved_value = row.substr(pos + 1);
          if (retrieved_key == key) {
              std::size_t currentPos = m_file.tellg();
              std::size_t row_length = row.length();
              m_file.seekp(currentPos - row_length);
              std::string newEntry = key + "," + value + "\n";
              m_file &lt;&lt; newEntry;
              return 0;
          }
      }
  
      getchar();
      return 0;
  }
  </code></pre>
  
  <p>This is the code I have written. But it does not work. It modifies the contents of the file as below :</p>
  
  <blockquote>
  <pre><code>Star,Treks
  Captain,America
  BlBlack,Dreamers
  Fighters
  </code></pre>
  </blockquote>