Skip to content

Instantly share code, notes, and snippets.

@JellyWX
Last active March 1, 2018 09:57
Show Gist options
  • Save JellyWX/770b5c7a03c8478d3690e9d82b1e7aa0 to your computer and use it in GitHub Desktop.
Save JellyWX/770b5c7a03c8478d3690e9d82b1e7aa0 to your computer and use it in GitHub Desktop.
C++ thing for converting the indentation scale of a file
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
int main(int argc, char* argv[]) {
std::ifstream open_file;
std::ofstream output;
if (argc != 3) {
std::cerr << "Error: Please provide 2 arguments" << std::endl;
return -1;
}
const std::string fname = argv[1];
const std::string indents_str = argv[2];
if (indents_str.find_first_not_of("0123456789") != std::string::npos) {
std::cerr << "Error: Argument 2 must be of type <unsigned integer>" << std::endl;
return -1;
}
const int indents = std::stoi(argv[2]);
std::vector<std::string> lines;
open_file.open(fname);
if (!open_file) {
return -1;
}
std::string x;
while (!open_file.eof()) {
std::getline(open_file, x);
lines.push_back(x + "\n");
}
open_file.close();
output.open(fname);
int indent_scale = 0;
int current_indentation = 0;
std::string spaces;
for (std::string line : lines) {
spaces = "";
current_indentation = 0;
for (char &c : line) {
if (c == ' ') {
current_indentation++;
} else {
break;
}
}
if (indent_scale == 0 && current_indentation != 0) {
indent_scale = current_indentation;
std::cout << "Indentation detected as " << indent_scale << std::endl;
}
if (indent_scale > 0) {
int set_to = (((double)current_indentation / (double)indent_scale) * indents);
std::cout << set_to << std::endl;
for (int i = 0; i < set_to; i++) {
spaces += " ";
}
}
std::string a = "";
bool exited_spaces = false;
for (char &c : line) {
if (!exited_spaces && c == ' ') {
continue;
} else {
exited_spaces = true;
a += c;
}
}
output << spaces << a;
}
output.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment