fin >> noskipws >> ch 始终为 false

fin >> noskipws >> ch is always false

我正在学习 C++。

我正在尝试转换这样的文本文件:

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,
       ...

像这样的文件:

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

这两个文本文件只是一个例子,向您展示我正在尝试做的事情。第一个文本文件不会生成第二个文本文件。

我记下了这段代码:

#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;
}

但是好像一直没有进入主循环(while (fin >> noskipws >> ch))。我在文本文件中得到这个输出:

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

我正在使用以下命令行在 Linux (Ubuntu) 上使用 g++ 进行编译:

g++ FormatMatrix.cpp -o format

我做错了什么?

在进入 while 循环之前检查 create/open 您的输入流 'fin' 是否成功。