第二行的列数较少"cuts off"第一行的列数较多
Lesser number of columns of the second row "cuts off" a bigger number of columns of the first row
*编辑:尽管如此,当第一行输入3列,第2行输入2列时,输出的第一行变成了2元素的第一行。
输出动态分配的设备数量与单独动态分配的列数(用于每个设备的捕获数量)的问题…也就是说,如果我尝试分配2个装备,然后第一个装备2条鱼(两列),第二个装备3条鱼,一切都没问题....但是如果我尝试为第二行(装备)输入较小数量的列("捕获"),那么在输出中,第一行的"多余"被"切断",因此,例如,如果有3列输入第一行和2列输入第二行,在输出中将只有两列(数字索引)对于每两行。
#include<iostream>
int main()
{
using namespace std;
int *sum;
int *a = new int;
int *b = new int;
cout << "Total number of equips: ";
cin >> *a;
// Allocate a two-dimensional 3x2 array of ints
int** ippArray = new int*[*a];
for (int i = 0; i < *a+1; ++i) {
ippArray[i] = new int[*b];
}
// fill the array
for (int i = 1; i < *a+1; ++i) {
cout << "Total number of catches for " << i << "th equip : ";
cin >> *b;
cout << "Equip number: " << i << endl;
for (int j = 1; j < *b+1; ++j) {
cout << "Catch number: " << j << endl;
cin >> ippArray[i][j];
ippArray[i][j];
}
}
// Output the array
for (int i = 1; i < *a+1; ++i) {
for (int j = 1; j < *b+1; ++j) {
cout << ippArray[i][j] << " ";
*sum = *sum + ippArray[i][j];
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << *sum-3;
// Deallocate
for (int i = 1; i < *a+1; ++i) {
delete [] ippArray[i];
}
delete [] ippArray;
// Keep the window open
cin.get();
return 0;
}
首先,除非确实需要,否则不要将整数转换为指针(int *a = new int;
)。这会让代码更难读,如果有人要维护你的代码,他们会叫你a-hole。
第二,int** ippArray = new int*[*a];
与您这样做的多个点相结合…for (int i = 1; i < *a+1; ++i)
不好。ippArray有从0到*a
的有效引用,因此它应该是for (int i = 0; i < *a; ++i)
编辑:试试这样http://ideone.com/4egQl3
编辑2:也是标准的建议…
{
std::vector<string> advice;
advice.push_back( "These will make your life easier" );
}
// No de-allocation needed!
程序中有未定义行为的部分
- 在赋值前使用*b
- 访问所有数组的越界元素
- 不要初始化sum
- 在赋值前使用*sum
清理后,代码变成
int main()
{
using namespace std;
int sum, a, b;
cout << "Total number of equips: ";
cin >> a;
typedef vector<vector<int> > vvint;
typedef vector<int> vint;
// Allocate a two-dimensional structure of ints
vvint ippArray(a);
// fill the array
for (vvint::size_t i = 0; i < a; ++i) {
cout << "Total number of catches for " << i+1 << "th equip : ";
cin >> b;
cout << "Equip number: " << i+1 << endl;
ippArray[i] = vint(b);
for (int j = 0; j < b; ++j) {
cout << "Catch number: " << j+1 << endl;
cin >> ippArray[i][j];
}
}
// Output the array
for (const vint & inner : ippArray) {
for (int num : inner) {
cout << num << " ";
sum += num;
}
cout << endl;
}
cout << endl;
cout << "All catches of the all equipes: " << sum;
cin.get();
return 0;
}
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 从C++dll访问C#中的一行主要参数
- 在C++中,我如何接受不同于同一行的用户输入
- 如何从一行中读取特定数量的字符?(C++)
- 读取最后一行代码算法 - c++ 时出现问题
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 有没有办法在一行中填充矢量图
- 需要将一行代码从C++ Qt翻译成PyQt
- 为什么如果我添加这一行,我的程序会不断询问值
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何使用运算符在同一行中多次调用函数
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 而(!inputfile.eof())只读取第一行?
- 这段代码的最后一行在做什么?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- C++找出覆盖同一行的数组
- 如何让字符数组在一行而不是多行中打印出来?