c-如何将文件中的单词存储在单独的变量中



在这段代码中,我想选择一个单词并将其保存在一个单独的变量中。与文件中的所有单词相同。我已经给出了从文件中选择任何单词的选项(我对此进行了评论(,当用户选择该单词时,它应该存储在一个变量中。如何做到这一点?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE * fr = fopen("file.txt", "r");
char string[100];
if((fr = fopen("file.txt", "r")) == NULL){
printf("Error! Opening file");
exit(1);
}
while (fgets(string, 100, fr) != NULL){
printf("%s", string);
// printf("Write word to extract: ");
// scanf("%s", ch);
fclose(fr);
}

当用户输入相同的单词时,我看不到有什么用。但给你。

使用scanf()作为要查找的单词的用户输入。使用fgets()将文件中的行转换为字符串。使用strtok()使用#define DELIMITERS中给定的分隔符逐步遍历字符串。

从文件中扫描的单词存储在saved_word中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DELIMITERS " ,.-_!?"
#define STRING_LEN 100
int main(){
FILE * fr = NULL;
char string[STRING_LEN]; // Buffer for row in file
char input[STRING_LEN]; // Buffer for input word
char saved_word[STRING_LEN]; // To save the word in
memset(string, 0, sizeof string);
memset(input, 0, sizeof input);
memset(saved_word, 0, sizeof saved_word);
fr = fopen("file.txt", "r");
if (fr == NULL)
{
printf("Error! Opening file");
exit(1);
}
char* word = NULL;
/**
* User input of word to look for within file
*/
printf("string: %sn", string);
printf("Enter what word you want to find: ");
scanf("%s", input);
printf("n");
printf("Start scanning file.n");
while (fgets(string, STRING_LEN-1, fr) != NULL)
{
printf("Scanned row.n");
/**
* Use strtok() to scan through the row, stored in string
* Manual says to only have string input parameter on first call
*/
word = strtok(string, DELIMITERS);

int diff;
while (word != NULL)
{
diff = strcmp(input, word);
if (diff == 0)
{
// Matching words! 
printf("Found the word: %sn", word);
strcpy(saved_word, word);
}
word = strtok(NULL, DELIMITERS);
}

}
fclose(fr);
}

我不确定我是否理解你写的

也许你可以从用户那里读一个单词;提取物";它从文件中,一个搜索。

为了让用户能够从文件中选择一个单词,必须将该单词读取到变量中。为了使程序能够将文件中的单词与变量中的单词进行比较,必须将文件中单词读取到另一个变量中。

在您的代码中,您要多次打开和关闭文件。看看吧。

最新更新