如何使用scanf()和while循环在c编程中将字符串从stdin读取到二维数组中?



我正在编写一个 c 代码,使用 scanf(( 和 while 循环(进入二维字符数组(从 stdin 读取字符串。我的策略是使用输入数组临时存储每个字符串,然后将其分配给前言数组(固定大小(。但是,我的策略失败了,存储在数组中的所有字符串都是相同的(最后一个字符串输入(。如何解决?

我使用了 fgets(( 并且它有效查找。但是,我不能使用它来处理新的字符串行(来自 stdin(。我的 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 %sn",count,preword[count]);
count++;
}
printf("the count is %dn",count);
for (int i = 0; i < count; i++){
printf("preword[%d] is %sn",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指出的那样,它的副本inputpreword的每个元素中,它是同一个指针,因为您没有为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 %sn",count,preword[count]);
count++;
}
else {
/* @TODO malloc erro handling */
}
}
printf("the count is %dn",count);
for (int i = 0; i < count && preword[i] != NULL; i++){
printf("preword[%d] is %sn",i,preword[i]);
free(preword[count]); /* free dynamically allocated memory here*/
}
return 0;
}

最新更新