[英]C - Printing a 2D Char Array
如何在C中打印2D字符數組的元素?
這是我當前的代碼:
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數組)。示例:
ab
cd
ef
gh
ij
kl
mn
op
而不是我想要的輸出:
abcd
efgh
ijkl
mnop
為什么是這樣?
更改scanf可解決所有問題
scanf(" %c",&word[k][j]); // notice the space before '%c'
而且您還需要將打印循環更改為此
for (k = 0; k < size; ++k){
for(j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
printf("\n");
}
我刪除了閱讀內容,看來可以打印了:
int main()
{
const unsigned int size = 4;
char word[size][size];
//Enter the matrix
for (int k = 0; k < (size); ++k) {
for (int j = 0; j < (size); ++j) {
word[k][j] = 'a' + j + (k * size);
}
}
for (int k = 0; k < size; ++k) {
for (int j = 0; j < size; ++j) {
printf("%c", word[k][j]);
}
printf("\n");
}
printf("\n");
getchar();
return 0;
}
並輸出:
abcd
efgh
ijkl
mnop
我發現您的來源有兩個問題。
一種是內存分配-實際上不是ansi-c。
如果需要動態內存,則需要在運行時分配它。 考慮使用c ++,因為有一些標准的工具可以更安全地為您提供幫助。
第二個問題是緩沖區中有一個空格字符用作輸入字符。 我想你想澄清一下。
這是帶有其他注釋的來源:
#include <stdio.h>
#include <stdlib.h>
void ansiC()
{
unsigned int size;
printf("Enter size:\n");
scanf("%d", &size);
//char word[size][size]; <- this is not ansi-c because size is unknown at compile time
char * word = (char*)malloc(sizeof(char)* 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 * size + j]);
//since word is just a pointer i changed the way the position is calculated
//after the character the user presses the enter key
//this puts a whitespace character on the buffer.
//by adding the space after %c you also clear that from the buffer
}
}
//printf("\n");
for (int k = 0; k < size; ++k)
{
for (int j = 0; j < size; ++j)
{
printf("%c", word[k * size + j]);
//since word is just a pointer i changed the way the position is calculated
}
//printf("\n ");
}
printf("\n");
free(word); //if you use malloc you need to remember to use free
}
int main()
{
ansiC();
return 0;
}
注意: %c
和%1s
做不同的事情(除了為后者添加終止null之外):
c
取每個字符, 包括空格,制表符,cr和lf %1s
跳過了所有空格(空格,制表符,cr,lf等) 因此,在輸入時間,您應該使用:
char c[2]; // provide room for a terminating null...
...
for(int k = 0; k < (size); ++k){
for (int j = 0; j < (size); ++j){
printf("Enter letter:");
scanf("%1s",c);
word[k][j] = c[0];
}
}
在打印時:
for (int k = 0; k < size; ++k){
for(int j = 0; j < size; ++j){
printf("%c",word[k][j]);
}
printf("\n "); // new line after each line
}
請檢查一下。
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
char arr[5][3]={"abc","aks","tny","dkn","kbf"};
for(int a=0;a<5;a++)
{
for(int b=0;b<3;b++)
{
cout<<" "<<arr[a][b];
}
cout<<endl;
}
getch();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.