下面的代码询问用户对2D数组大小的输入并输出如下内容:(比如一个18x6网格)
..................
..................
..................
..................
..................
..................
代码从这里开始:
#include <stdio.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
我现在向用户询问一个字符串,然后询问他们在哪里放置它:
Please enter grid size: 18 6
Please enter word: Hello
Please enter location: 0 0
Output:
Hello.............
..................
..................
..................
..................
..................
Please enter location: 3 4
Output:
..................
..................
..................
..Hello...........
..................
..................
program just keeps going.
有关如何修改此代码的想法吗?
PS:垂直看起来很难,但我想先从横向开始做一些事情。
答案 0 :(得分:0)
#include <stdio.h>
#include <string.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row, col;
char word[MAX];
int row_w,col_w;
int word_len;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
printf("Please enter word: ");
scanf("%s", word);
word_len = strlen(word);
printf("Please enter location: ");
scanf("%d %d", &row_w, &col_w);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
}
}
for (j = col_w; j < col_w + word_len; j ++) {
grid[row_w][j] = word[j - col_w];
}
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}