【发布时间】:2019-12-07 07:32:41
【问题描述】:
我正在尝试替换 '.'在我的数组中带有'O',但它会将其插入其中而不是取代它的位置。请帮助我不知道我做错了什么。
#include <iostream>
using namespace std;
char** createField(int w, int l)
{
int obstacles;
char ** arr = new char * [w];
for(int i=0; i<w; i++)
{
arr[i] = new char[l];
}
//Initializing the values
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
arr[i][j] = 0;
}
}
cout<<"Enter number of obstacles: ";
cin>>obstacles;
int x=0;
int y=0;
for (int j = 0; j < obstacles; ++j) {
cout<<"Enter location of obstacles: ";
cin>>x>>y;
arr[x][y] ='O';
}
for(int i = 0; i < w; ++i)
{
for(int j = 0; j < l; ++j)
{
if(i==0 || i == w-1){
cout<< arr[i][j]<< 'W';
}else if(j==0 || j==l-1){
cout<< arr[i][j]<< 'W';
} else
cout<< arr[i][j]<< '.';
}
cout<<"\n";
}
return arr;
}
int main() {
int w;
int l;
cout << "Enter the Width: ";
cin >> w;
cout << "Enter the length: ";
cin >> l;
//Pointer returned is stores in p
char **p = createField(w, l);
//Do not Forget to delete the memory allocated.It can cause a memory leak.
for (int del = 0; del < w; del++) {
delete[] p[del];
}
delete[]p;
}
这是我的输出示例,我希望用 'O' 替换 '.'而不是介于两者之间。另外,如果有人可以解释为什么会发生这种情况,那将非常有帮助,谢谢。
输出示例:w.O.w
期望的输出:w.Ow
【问题讨论】:
-
首先,我有一个问题:您认为
cout<< arr[i][j]<< '.'将发送多少个字符到标准输出?或者cout<< arr[i][j]<< 'W'怎么样? -
它假设是用户输入的值,所以如果用户输入 10 的宽度和 11 的长度,数组将相应地自行调整。
-
我不是在问有多少循环迭代;我只是在询问这两个陈述。 就是这样。是 1 吗? 2 ? 3 ?
-
我很确定只有 1。我对编程还是很陌生,如果不准确,请见谅。
-
这是两个。 (抱歉,正在与嘉宾 Gordon Ramsey 一起观看 Hot Ones 剧集。天哪,那是 FaF。)。这意味着每次执行
cout<< arr[i][j]<< 'W'或cout<< arr[i][j]<< '.'时,都会打印两个 字符:a[i][j]中的内容,以及尾随字符W或.。把它写在纸上,看看它现在是否有意义,你得到的输出。
标签: c++