![](/img/trans.png)
[英]How to store and then print a 2d character/string array horizontally for 5 times?
[英]how to store and then print a 2d character/string array?
假設我有:老虎,獅子,長頸鹿。
我怎樣才能將其存儲在一個二維char
使用數組for
循環和scanf
,然后用打印字一個一個for
循環?
就像是
for(i=0;i<W;i++)
{
scanf("%s",str[i][0]); //to input the string
}
PS很抱歉提出這樣一個基本問題,但我在Google上找不到合適的答案。
首先,您需要創建一個字符串數組。
char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];
然后,您需要將字符串輸入數組
int i;
for (i=0; i<NUMBER_OF_WORDS; i++) {
scanf ("%s" , arrayOfWords[i]);
}
最后在oreder打印它們使用
for (i=0; i<NUMBER_OF_WORDS; i++) {
printf ("%s" , arrayOfWords[i]);
}
char * str[NumberOfWords];
str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral\0");
//Initialize more;
for(int i = 0; i < NumberOfWords; i++){
scanf("%s", str[i]);
}
你可以這樣做。
1)創建一個字符指針數組。
2)動態分配內存。
3)通過scanf獲取數據。 下面是一個簡單的實現
#include<stdio.h>
#include<malloc.h>
int main()
{
char *str[3];
int i;
int num;
for(i=0;i<3;i++)
{
printf("\n No of charecters in the word : ");
scanf("%d",&num);
str[i]=(char *)malloc((num+1)*sizeof(char));
scanf("%s",str[i]);
}
for(i=0;i<3;i++) //to print the same
{
printf("\n %s",str[i]);
}
}
#include<stdio.h>
int main()
{
char str[6][10] ;
int i , j ;
for(i = 0 ; i < 6 ; i++)
{
// Given the str length should be less than 10
// to also store the null terminator
scanf("%s",str[i]) ;
}
printf("\n") ;
for(i = 0 ; i < 6 ; i++)
{
printf("%s",str[i]) ;
printf("\n") ;
}
return 0 ;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.