![](/img/trans.png)
[英]How do I read a list of strings from file into a dynamic two-dimensional array and then sort it in C
[英]How to read strings from stdin into a two-dimensional array in c programming using scanf() and while loop?
我正在编写 ac 代码以使用 scanf() 和 while 循环从 stdin 读取字符串(到二维字符数组中)。 我的策略是使用一个输入数组来临时存储每个字符串,然后将其分配给一个 preword 数组(固定大小)。 但是,我的策略失败了,存储在数组中的所有字符串都相同(最后一个字符串输入)。 如何解决?
我使用了 fgets() 并且它可以找到。 但是,我不能用它来处理新的字符串行(来自标准输入)。 我的 fgets() 只读取第一行,这就是我转向 scanf 和 while 循环的原因。
#include<stdio.h>
#include<stdlib.h>
#define MAX 1000
#define size 50
int main ()
{
int count = 0;
char input[size];
char * preword[MAX];
while (scanf("%s",input)!= EOF){
preword[count] = input;
printf("preword[%d] is %s\n",count,preword[count]);
count++;
}
printf("the count is %d\n",count);
for (int i = 0; i < count; i++){
printf("preword[%d] is %s\n",i,preword[i]);
}
return 0;
}
我希望来自 stdin 的输入数组将存储在二维字符数组中。 以下是编译后终端中的输出。 我的输入是一个txt文件,其中我有
hello world
I am a hero
事实证明,存储在二维数组中的所有字符串都是最后一个字。
preword[0] is hello
preword[1] is world
preword[2] is I
preword[3] is am
preword[4] is a
preword[5] is hero
the count is 6
preword[0] is hero
preword[1] is hero
preword[2] is hero
preword[3] is hero
preword[4] is hero
preword[5] is hero
首先在这里
char * preword[MAX];
preword
是字符指针数组,即每个元素都是一个字符指针 & 当你这样做时
preword[count] = input;
由于@paddy 在preword
每个元素中都指出了它的副本input
,并且它是相同的指针,因为您没有为preword[count]
分配内存,正确的方法是为每个指针分配内存然后复制。
在这里也使用fgets()
而不是scanf()
。 例如
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 1000
#define size 50
int main (void)
{
int count = 0;
char input[size] = {0};
char * preword[MAX] = {0};
size_t retStrCspn = 0;
while (fgets(input, size, stdin) != NULL){
/* remove trailing new line if its stored at end of buffer by fgets() */
input[retStrCspn = strcspn(input, "\n")] = 0; /* remove the trailing & use the return value for allocating memory purpose \n */
preword[count] = malloc(retStrCspn + 1); /* Allocate memory for each pointer elements */
if(preword[count] != NULL) {
memcpy (preword[count], input, retStrCspn + 1); /* copy input buffer into each different memory location */
printf("preword[%d] is %s\n",count,preword[count]);
count++;
}
else {
/* @TODO malloc erro handling */
}
}
printf("the count is %d\n",count);
for (int i = 0; i < count && preword[i] != NULL; i++){
printf("preword[%d] is %s\n",i,preword[i]);
free(preword[count]); /* free dynamically allocated memory here*/
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.