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: %s\n", 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: %s\n", word);
strcpy(saved_word, word);
}
word = strtok(NULL, DELIMITERS);
}
}
fclose(fr);
}
推荐阅读
- python-3.x - 如何从同一个模块导入
- python - 使用 pd.melt 将列转换为两个单独的变量值列
- c# - 忽略泛型类型的类型参数约束
- android - 使用 Visual Studio 创建 firebase Robo 文件
- r - 在r中使用prcomp for PCA时显示对应PC的名称
- reactjs - 如何使用 react-native 设计字段集图例
- python - Pandas/Python 如何为特定变量值创建平均值?
- .net - 无法解析 Json。原始结果 .NET Core
- laravel - 如何修复'文件....在 Laravel 中不存在?
- python - 为什么 pytest 不运行我的测试并跳过它们