Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从数组中添加值并插入空间_C++_Arrays - Fatal编程技术网

C++ 从数组中添加值并插入空间

C++ 从数组中添加值并插入空间,c++,arrays,C++,Arrays,我有一个二维整数数组,如主函数所示。程序需要提示用户输入一个整数。然后,我必须使用“addValue”函数将用户的值添加到2D数组中的每个值中,如主函数中所示 然后,编写“print”函数,打印出数组中的值,数组中的每一行都在自己的行上,每一行中的每个数字都用一个空格分隔 注意:我不应该在每行最后一个数字后打印空白。 例如: Input: 2 Output: 7 6 25 1 我的问题是,我需要在输出中有一个空间,但我只得到某些输入值的空间。例如,当输入为-1时,我得到 输出: 43 2

我有一个二维整数数组,如主函数所示。程序需要提示用户输入一个整数。然后,我必须使用“addValue”函数将用户的值添加到2D数组中的每个值中,如主函数中所示

然后,编写“print”函数,打印出数组中的值,数组中的每一行都在自己的行上,每一行中的每个数字都用一个空格分隔

注意:我不应该在每行最后一个数字后打印空白。

例如:

Input:
2

Output:

7 6

25 1
我的问题是,我需要在输出中有一个空间,但我只得到某些输入值的空间。例如,当输入为-1时,我得到 输出:

43
22-2      
输出

4242 42
因此,在示例代码中,23需要2个字符,-1需要2个字符。他们挤在一起,以23比1获胜

解决方案: 强迫空间

cout<<setw(2)<<my_array[i][j] << ' '; 
好吧,那100美元太过分了,但你明白了。你也可以把空间放在第一位

cout<<setw(2)<<' ' << my_array[i][j]; 
如果必须为
循环保留
,请打印第一个不带任何装饰的元素,然后使用前面的空格打印其余元素

for(int i=0;i<2;i++)
{
    cout<< my_array[i][0];  
    for(int j=1;j<2;j++)
    {
        cout<< ' ' <<my_array[i][j];  
    }
    cout<<endl;
}

for(int i=0;我希望您的数字总是2位或更少?如果不是,那么您的问题不仅在于空格,还在于
setw()调用中的
2
4242 42
cout<<setw(2)<<my_array[i][j] << ' '; 
cout<<setw(100)<<my_array[i][j]; 
cout<<setw(2)<<' ' << my_array[i][j]; 
cout << my_array[i][0] << ' ' << my_array[i][1]; 
for(int i=0;i<2;i++)
{
    cout<< my_array[i][0];  
    for(int j=1;j<2;j++)
    {
        cout<< ' ' <<my_array[i][j];  
    }
    cout<<endl;
}