[英]Store string into array in c
據我所知,我可以創建一個包含項目的數組,例如:
char *test1[3]= {"arrtest","ao", "123"};
但是如何將我的輸入存儲到上面的代碼中,因為我只能將其編碼為
input[10];
scanf("%s",&input) or gets(input);
它將每個char存儲到每個空間中。
如何存儲輸入“HELLO” ,使其存儲到input [0]中,但現在
H輸入[0],E輸入[1],依此類推。
你需要一個二維字符數組來擁有一個字符串數組:
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
使用二維數組char input[3][10];
要么
一個char
指針數組(如char *input[3];
),應該在這些位置保存任何值之前動態分配內存。
第一種情況,將輸入值作為scanf("%s", input[0]);
,類似於input[1]
和input[2]
。 請記住,您可以在每個input[i]
存儲最大大小為10
的字符串(包括'\\0'
字符)。
在第二種情況下,以與上面相同的方式獲取輸入,但是使用malloc
之前為每個指針input[i]
分配內存。 在這里,您可以靈活地調整每個字符串的大小
真的不明白你需要什么。 但這是我猜的。
char *a[5];//array of five pointers
for(i=0;i<5;i++)// iterate the number of pointer times in the array
{
char input[10];// a local array variable
a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here
scanf("%s",input);//take the input from stdin
strcpy(a[i],input);//store the value in one of the pointer in the pointer array
}
嘗試以下代碼:
char *input[10];
input[0]=(char*)malloc(25);//mention the size you need..
scanf("%s",input[0]);
printf("%s",input[0]);
int main()
{
int n,j;
cin>>n;
char a[100][100];
for(int i=1;i<=n;i++){
j=1;
while(a[i][j]!=EOF){
a[i][j]=getchar();
j++;
}
}
這段代碼激發了我如何將用戶輸入字符串轉換為數組。 我是新來的C和這個董事會,如果我沒有遵守關於如何發表評論的規則,我表示歉意。 我正在努力解決問題。
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.