gpt4 book ai didi

c++ - fin >> noskipws >> ch 始终为 false

转载 作者:行者123 更新时间:2023-11-27 23:39:46 25 4
gpt4 key购买 nike

我正在学习 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 循环之前,检查创建/打开输入流“fin”是否成功。

关于c++ - fin >> noskipws >> ch 始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56289411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com