鳍>> noskipws >> ch始终为假

时间:2019-05-24 09:13:31

标签: c++ fstream

我正在学习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

我在做什么错了?

1 个答案:

答案 0 :(得分:3)

在进入while循环之前,检查创建/打开输入流'fin'是否成功。

相关问题