Skip to content

Instantly share code, notes, and snippets.

@trasa
Created December 2, 2021 05:51
Show Gist options
  • Save trasa/6d016f75beb3b3c19600e1c01c08e874 to your computer and use it in GitHub Desktop.
Save trasa/6d016f75beb3b3c19600e1c01c08e874 to your computer and use it in GitHub Desktop.
Quick and dirty string parsing in C++
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
// our data to be "serialized"
int turnNumber = 5;
int xPos = 6;
int yPos = 7;
// serialize into a comma delimited string...
std::string s = std::to_string(turnNumber) + "," + std::to_string(xPos) + "," + std::to_string(yPos);
std::cout << s << std::endl; // for debugging
// deserialize into some new variables
int retrievedTurnNumber = -1;
int retrievedXPos = -1;
int retrievedYPos = -1;
// this is just one way to do this...
vector<string> parts;
stringstream ss(s);
// chop 's' into parts
while (ss.good())
{
string substr;
getline(ss, substr, ',');
parts.push_back(substr);
}
retrievedTurnNumber = stoi(parts[0]);
retrievedXPos = stoi(parts[1]);
retrievedYPos = stoi(parts[2]);
std::cout << retrievedTurnNumber << "," << retrievedXPos << "," << retrievedYPos << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment