嘿伙计们,所以我试图从输入文件中取出单词并与它们一起玩,以便按照一定的顺序(我相信我已经正确完成)。
我的问题是,我不认为任何单词实际上是进入单词数组,因为当我打印它没有任何显示。如果我想从文件中取出单词并进入单词数组。我做错了什么?
while (fscanf(file, "%s", word) == 1)
{
wc = strtok(word, " \n");
while (wc != NULL)
{
wc = strtok(NULL, " \n");
count++;
}
答案 0 :(得分:1)
while (fscanf(file, "%s", word) == 1)
我看到你正在使用fscanf()
和%s
所以基本上你只是从文件中提取一个单词,然后你试图将这个单词分成标记,假设你已经获取了该行。
使用
char buf[100];
int count = 0;
while(fgets(buf, sizeof(buf),file) != NULL)
{
// Break the line into words using space as delimiter and copy it to the words array
char *p = strtok(buf," ");
while(p != NULL)
{
// strcpy(words[count],p); If you wish to copy the words into an array
count ++;
p = strtok(NULL," ");
}
}
printf("Number of words in the file are %d\n",count);