每行添加整数并将其存储在数组中

时间:2014-02-08 00:14:02

标签: c++ arrays

我正在尝试使用动态分配的数组而不是向量来创建一个迷你函数,因为我试图弄清楚它们是如何工作的。

基本上,用户输入他们想要的行数,然后,他们输入一组由空格分隔的整数/双精度。然后,我希望函数计算每行中的整数总和,将其分配到数组中。

例如:

3
1 2 3 4
3 2 2 1 //assume each line has the same # of integers (4)
1 4 4 1

然后,如果我实现了我的功能,则总和将为10,8,10。

到目前为止,我有这个:

int* total //is there a difference if I do int *total ??
int lines;
std::cout << "How many lines?;
std::cin >> lines;
total = new int[lines];

for (int i=0;i<lines;i++)
{
    for (int j=0;j<4;j++)
    {
        total[i] = ? //i'm confused how you add up each line and then put it in the array, then go onto the next array..
     }
 }

如果有什么不合理的话,请随时问!谢谢!

4 个答案:

答案 0 :(得分:2)

您可能希望在内循环之前将total[i]设置为0,然后使用operator+=添加从std::cin流中获得的任何内容。< / p>

// ...
total[i]=0;
for (int j=0;j<4;j++)
{
    int temp;
    cin >> temp;
    total[i] += temp;
}
// ...

如果您首先分配一个数组来存储值然后将它们添加到一起,可能会更容易理解。

答案 1 :(得分:0)

首先,您需要分配一个数组数组来存储每行的数字。例如

const size_t COLS = 4;
size_t rows;
std::cout << "How many lines? ";
std::cin >> rows;

int **number = new int *[rows];

for ( size_t i = 0; i < rows; i++ )
{
   number[i] = new int[COLS];
}

int *total = new int[rows];
// or int *total = new int[rows] {}; that do not use algorithm std::fill

std::fill( total, total + rows, 0 );

之后你应该输入数字并填写每行数字。

答案 2 :(得分:0)

执行int* totalint *total之间没有任何区别(在您的示例中无论如何)。就个人而言,我更喜欢第二个。

至于你的问题,你需要将你的总数设置为一个初始值(在这种情况下你要将它设置为零),然后从那里获得cin的值后加上它。

使用cin,因为你有空格,它会得到每个单独的数字(如你所知,我是假设)但是你可能应该(我愿意)将这个数字存储到另一个变量然后将该变量添加到该行的总计中。

我认为一切都有道理。希望它有所帮助。

答案 3 :(得分:-2)

恕我直言,你可以使用二维数组来做到这一点:

int** total;

// ...

total = new int*[lines];

for(int i = 0; i < lines; ++i)
{
    total[i] = new int[4];   // using magic number is not good, but who cares?

    for(int j = 0; j < 4; ++j)
    {
        int tmp;
        std::cin>>tmp;
        total[i][j] = tmp;
    }
}

// do sth on total

for(int i = 0; i < lines; ++i)
    delete[] total[i];

delete[] total;