我正在学习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_filen";
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
我在做什么错?
在输入时循环之前,请检查/打开输入流'fin'是否成功。