gpt4 book ai didi

将一个字符串与文件中的另一个字符串进行比较

转载 作者:行者123 更新时间:2023-11-30 19:18:14 24 4
gpt4 key购买 nike

关闭。这个问题需要更多 focused .它目前不接受答案。












想改进这个问题?更新问题,使其仅关注一个问题 editing this post .

7年前关闭。




Improve this question




我想知道如何将字符串数组与文件中的字符串进行比较。

这里的借口是,我有一个单词数组,我想将它们与我创建的文本文件进行比较,以确保字符串数组与文件中的字符串不匹配。

我不知道如何解决这个问题,建议我使用 fscanf(...)、fgets(...) 或 fgetc(...),但我不太确定它们是如何工作的。你能解释一下如何阅读文本文档中的字符串吗?

我假设比较它们我使用strcmp?如果我错了纠正我。

这是我得到的内容,以及我写的内容是否无法理解或您是否需要更多信息的问题。

int validName(const char name[ ]);


#include <stdio.h> /* DO NOT MODIFY ANY PART OF THIS CODE EXCEPT
the function int validName(const char name[ ]) */
#include <stdlib.h>
#include <string.h>

#define ROWS 20
int validName(const char name[ ]);


int main( ) {
char identifiers[ROWS][13] = { /* an array of strings */
"isValid", "if", "floats", "array", "char",
"take_break", "name*", "8values", "break_time", "structure",
"register", "for ", " do", "ok_to_go", "_isThisValid",
"goto", "const", "void", "continue", "taxed2much" };

int i, result,
valid[ROWS] = {1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1 };
for(i=0; i<ROWS; i++) {
result = validName(identifiers[i]);
printf("identifier: %-15s your return: (%-6s) name should be: %-9s you say: %s\n",
identifiers[i], result ? "TRUE" : "FALSE" , valid[i] ? "VALID" : "INVALID",
result ? "VALID" : "INVALID");
}
return 0;
}

int validName(const char name[ ]) {
FILE *compareFile;
compareFile = fopen("keywords.txt", "r");
if(compareFile == NULL){
printf("error opening file… \n");
exit(EXIT_FAILURE);
} else{

}

}


/* Recall: An identifier is valid if it contains ONLY letters, digits and underscore
characters in any order. Also, the first character may not be a digit AND the name of the
identifier *MAY NOT* be a keyword. For this LAB keywords are stored as records in a text
file named keywords.txt. Each record contains a single keyword followed by the
newline. You may assume the file will be in the program's current working directory.
You can read data from a file by using the fscanf(...), fgets(...), or fgetc(...)
functions. */

最佳答案

这取决于您要查找的字符串。如果它们只是文字,它会变得容易得多。

无论如何,首先我会用 fgetc() 将整个文件读入缓冲区。之后继续使用strtok()以空格作为分隔符。

然后对于每个 token 使用 strcmp()在 token 和您拥有的双字符数组上。
这可能需要一些技巧,例如剥离换行符之类的东西。最简单的方法是不要将它们写入缓冲区并跳到下一个字符。

如果它们不是单词,则必须找到要查找的字符串的最大长度。
然后定义该长度的区域并逐字节检查整个缓冲区。

如果您有更多信息,我可以举个例子

关于将一个字符串与文件中的另一个字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27003625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com