Pages

Wednesday, July 24, 2013

C++ vs Python: Converting tabs to spaces

For a Python programmer, eventually you have to deal with some odd files where the indentation are done via tabs rather than spaces, and you need to standardise it to spaces. In C++ this is how you do it.
#include <iostream> #include <fstream> #include <cstdlib> using namespace std; int main(int argc, char** argv) { if (argc &lt; 3) return(EXIT_FAILURE); ifstream in(argv[1]); ofstream out(argv[2]); if (!in || !out) return(EXIT_FAILURE); char c; while (in.get(c)) { if (c == '\t') out &lt;&lt; " "; // 4 spaces else out &lt;&lt; c; } out.close(); if (out) return(EXIT_SUCCESS); else return(EXIT_FAILURE); } </cstdlib></fstream></iostream> In Python, after you have read in the file or line, you simply do:
spacestring = tabstring.expandtab();

No comments:

Post a Comment