任何人都可以修复此示例代码,该代码将以2D数组打印文件。这是代码和输出。
while (!file.eof())
{
int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
输出不是表格形式。
输出结果为:
指数尺寸重量(磅/英尺)直径(英寸)0 2 0.167 0.250 1 3 0.376 0.375 2 4 0.668 0.500 3 5 1.043 0.625 4 7 1.502 0 6 9 2.670 1.000 7 12 3.400 1.128 8 14 4.303 1.270 1.270
按任意键继续。 。
答案 0 :(得分:0)
两个选项:
将coutner
定义为静态
while (!file.eof())
{
static int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
或将其定义为while循环的外部:
int counter = 0;
while (!file.eof())
{
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
如果你定义它并在while循环的iteratoin中将它初始化为0 - 它将永远不会达到5来打印endl;
答案 1 :(得分:0)
似乎不仅计数器在每个循环中被初始化,正如其他人在我之前指出的那样,而且,它实际上从未实际增加。我看到的唯一增加是在它等于五的条件下。因为它永远不会在条件之外增加,它永远不会达到五(即使它被声明为静态或在循环之外),因此从未满足条件。
你也有不均匀的开合花括号。
我不确定你想要达到什么目标。如果您希望在每第五次迭代后换行,则以下内容应该有效:
int counter = 0;
cout << setw(4) // suffice to set once
while (!file.eof())
{
file >> n;
cout << n << " ";
if (++counter == 5) // increase here before checking condition
{
cout << endl;
counter = 0;
// do not increase here again
}
}