[英]Store string into array in c
As i know, i can create an array with item inside such as: 据我所知,我可以创建一个包含项目的数组,例如:
char *test1[3]= {"arrtest","ao", "123"};
but how can i store my input into array like code above because i only can code it as 但是如何将我的输入存储到上面的代码中,因为我只能将其编码为
input[10];
scanf("%s",&input) or gets(input);
and it store each char into each space. 它将每个char存储到每个空间中。
How can i store the input "HELLO" such that it stores into input[0] but now 如何存储输入“HELLO” ,使其存储到input [0]中,但现在
H to input[0],E to input[1], and so on. H输入[0],E输入[1],依此类推。
You need a 2 dimensional character array to have an array of strings: 你需要一个二维字符数组来拥有一个字符串数组:
#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]);
}
Use a 2-dimensional array char input[3][10];
使用二维数组
char input[3][10];
or 要么
an array of char
pointers (like char *input[3];
) which should be allocated memory dynamically before any value is saved at those locations. 一个
char
指针数组(如char *input[3];
),应该在这些位置保存任何值之前动态分配内存。
First Case, take input values as scanf("%s", input[0]);
第一种情况,将输入值作为
scanf("%s", input[0]);
, similarly for input[1]
and input[2]
. ,类似于
input[1]
和input[2]
。 Remember you can store a string of max size 10
(including '\\0'
character) in each input[i]
. 请记住,您可以在每个
input[i]
存储最大大小为10
的字符串(包括'\\0'
字符)。
In second case, get input the same way as above, but allocate memory to each pointer input[i]
using malloc
before. 在第二种情况下,以与上面相同的方式获取输入,但是使用
malloc
之前为每个指针input[i]
分配内存。 Here you have flexibility of size for each string. 在这里,您可以灵活地调整每个字符串的大小
Did not really understand what you need. 真的不明白你需要什么。 But here is what I guessed.
但这是我猜的。
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
}
try below code: 尝试以下代码:
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++;
}
}
This code inspired me on how to get my user input strings into an array. 这段代码激发了我如何将用户输入字符串转换为数组。 I'm new to C and to this board, my apologies if I'm not following some rules on how to post a comment.
我是新来的C和这个董事会,如果我没有遵守关于如何发表评论的规则,我表示歉意。 I'm trying to figure things out.
我正在努力解决问题。
#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.