0

I'm learning C++.

I'm trying to convert a text file like this one:

1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       ...

Into a file like this one:

int grid[20][30] = 
    { 
        { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, 

Both piece of text file are only and example to show you what I'm trying to do. The first text file doesn't generate the second text file.

I have written down this code:

#include <bits/stdc++.h>

using namespace std;

int main(int argc, char *argv[])
{
    if ((argc == 1) || (argc != 5)) {
        cout << "Usage: format rows columns input_file output_file\n";

        return 0;
    }

    // Number of rows in the image.
    int rows = atoi(argv[1]);
    // Number of columns in the image.
    int columns = atoi(argv[2]);
    // Character read from the input file.
    char ch;
    // Counter to create arrays of "columns" elements.
    int colCount = 0;
    // Counter for the number of rows added to the grid.
    int rowCount = 0;

    // Output file.
    ofstream fout;
    fout.open(argv[4], ios::out);

    // Write the header to output file.
    fout << "int grid[" << rows << "][" << columns << "] = {";

    // Read input file.
    fstream fin(argv[3], fstream::in);
    while (fin >> noskipws >> ch)
    {
        if (colCount == 0)
            fout << "\n{";

        if ((!isspace(ch)) && ((ch == '1') || (ch == '0') || (ch == ','))) {
            fout << ch;
            colCount++;
        }

        if (colCount == columns) {
            colCount = 0;
            rowCount++;
            if (rowCount != rows)
                fout << "},";
        }
    }

    fout << "}};\n";
    fout.close();

    return 0;
}

But it seems that it never enters into the main loop (while (fin >> noskipws >> ch)). I get this output in the text file:

int grid[365][484] = {}};

I'm compiling with g++ on Linux (Ubuntu) with the following command line:

g++ FormatMatrix.cpp -o format

What am I doing wrong?

VansFannel
  • 45,055
  • 107
  • 359
  • 626

1 Answers1

3

Check if create/open your input stream 'fin' succeeded before you enter the while loop.

Mathias Schmid
  • 431
  • 4
  • 7