Skip to content

Instantly share code, notes, and snippets.

@allekmott
Created February 23, 2016 19:16
Show Gist options
  • Save allekmott/cca17a0da8cc54821e20 to your computer and use it in GitHub Desktop.
Save allekmott/cca17a0da8cc54821e20 to your computer and use it in GitHub Desktop.
Simplifies single-line matrix formatting
#include <iostream>
#include <string>
#include <cstdlib>
#include <queue>
using namespace std;
void usage(string cmd) {
cout << "Usage: " << cmd << " [rows] [cols]" << endl;
}
int main(int argc, const char **argv) {
int rows, cols;
if (argc < 3) {
usage(argv[0]);
return 0;
}
rows = atoi(argv[1]);
cols = atoi(argv[2]);
cout << "Input " << rows << " rows, line separated (" << cols << " columns space separated): " << endl;
queue<string> rowVals;
for (int row = 0; row < rows; row++) {
string in;
getline(cin, in);
rowVals.push(in);
}
cout << "[";
for (int row = 0; row < rows; row++) {
cout << "[";
string rowComma = (row == rows - 1) ? "" : ",";
string rowString = rowVals.front();
for (int i = 0; i < rowString.length(); i++) {
if (rowString[i] == ' ')
cout << ",";
else
cout << rowString[i];
}
rowVals.pop();
cout << "]" << rowComma;
}
cout << "]" << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment