将输入文件中的单词输入数组
Entering words from input file into array
大家好,我正在尝试从输入文件中提取单词并使用它们将它们按特定顺序排列(我相信我做对了)。
我的问题是,我认为没有任何单词真正进入单词数组,因为当我打印它时,什么也没有显示。如果我想从文件中获取单词并将其放入单词数组中。我做错了什么?
while (fscanf(file, "%s", word) == 1)
{
wc = strtok(word, " \n");
while (wc != NULL)
{
wc = strtok(NULL, " \n");
count++;
}
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);
大家好,我正在尝试从输入文件中提取单词并使用它们将它们按特定顺序排列(我相信我做对了)。
我的问题是,我认为没有任何单词真正进入单词数组,因为当我打印它时,什么也没有显示。如果我想从文件中获取单词并将其放入单词数组中。我做错了什么?
while (fscanf(file, "%s", word) == 1)
{
wc = strtok(word, " \n");
while (wc != NULL)
{
wc = strtok(NULL, " \n");
count++;
}
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);