C-打印2D字符数组 [英] C - Printing a 2D Char Array
本文介绍了C-打印2D字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C中打印2D字符数组的元素?
How do I print the elements of a 2D Char Array in C?
这是我当前的代码:
int main()
{
unsigned int size;
printf("Enter size:\n");
scanf("%d",&size);
char word[size][size];
//Enter the matrix
for(int k = 0; k < (size); ++k){
for (int j = 0; j < (size); ++j){
printf("Enter letter:");
scanf("%c",&word[k][j]);
}
}
//printf("\n");
for (int k = 0; k < size; ++k){
for(int j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
//printf("\n ");
}
printf("\n");
}
执行时,它成对返回元素(使用4x4数组)
示例:
When executed it returns the element in pairs (using a 4x4 array) Example:
ab
cd
ef
gh
ij
kl
mn
op
而不是我想要的输出:
abcd
efgh
ijkl
mnop
这是为什么?
推荐答案
更改scanf解决了所有问题
changing your scanf solves all the problems
scanf(" %c",&word[k][j]); // notice the space before '%c'
之前的空格,并且您还需要将打印循环更改为此
And also you need to change your printing loop to this
for (k = 0; k < size; ++k){
for(j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
printf("\n");
}
这篇关于C-打印2D字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文