我试图从 txt 文件中取出每个单词,然后将其放入数组中。我的代码可以毫无问题地从文件中获取每个单词并将其保存为字符串。但是,当我尝试将字符串放入数组并将其打印出来时,只打印出最后几行,并且它全部扭曲了。
这是我的代码:
typedef char * string;
string strings[100];
FILE* file = fopen(argv[1], "r");
char line[256];
while(fgets(line, sizeof(line), file))
{
string tmp = strtok(line, " ,'.-");
while(tmp != NULL)
{
strings[count]= tmp;
tmp = strtok(NULL, " ,.'-;");
count++;
}
}
int c2 = 0;
while(strings[c2] != NULL)
{
printf("%s, ", strings[c2]);
c2++;
}
return 0;
}
这是我正在读取的文件中的文本:
There is a place where the sidewalk ends And before the street begins, And there the grass grows soft and white, And there the sun burns crimson bright, And there the moon-bird rests from his flight To cool in the peppermint wind.
最佳答案
几个明显的问题:
strings[count]= tmp;
这只是一个指针赋值。每次分配时 tmp 都有相同的值。每次循环都需要分配一个新字符串。并使用strcpy复制它。
其次,您的打印循环假设字符串数组是用空指针初始化的。它不是。您根本没有初始化它。
关于c - 当放入c中的数组时,字符串会变形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15712924/