我制作了一个简单的拼写检查器,它读入字典和用户文本文件来检查它。程序需要显示不在字典中的任何单词的行和单词索引。所以它工作正常,直到用户文本文件中有一个返回\n
字符(在段落或句子的末尾)。所以Hello实际上是对Hello\n
字典进行了测试,程序认为拼写错误。任何人都可以建议删除\n
字符的方法吗?这是我的代码:
#include <stdio.h>
#include <string.h>
void StrLower(char str[])
{
int i;
for (i = 0; str[i] != '\0'; i++)
str[i] = (char)tolower(str[i]);
}
int main (int argc, const char * argv[]) {
FILE *fpDict, *fpWords;
fpWords = fopen(argv[2], "r");
if((fpDict = fopen(argv[1], "r")) == NULL) {
printf("No dictionary file\n");
return 1;
}
char dictionaryWord[50]; // current word read from dictionary
char line[100]; // line read from spell check file (max 50 chars)
int isWordfound = 0; // 1 if word found in dictionary
int lineCount = 0; // line in spellcheck file we are currently on
int wordCount = 0; // word on line of spellcheck file we are currently on
while ( fgets ( line, sizeof line, fpWords ) != NULL )
{
lineCount ++;
wordCount = 0;
char *spellCheckWord;
spellCheckWord = strtok(line, " ");
while (spellCheckWord != NULL) {
wordCount++;
spellCheckWord = strtok(NULL, " ,");
if(spellCheckWord==NULL)
continue;
StrLower(spellCheckWord);
printf("'%s'\n", spellCheckWord);
while(!feof(fpDict))
{
fscanf(fpDict,"%s",dictionaryWord);
int res = strcmp(dictionaryWord, spellCheckWord);
if(res==0)
{
isWordfound = 1;
break;
}
}
if(!isWordfound){
printf("word '%s' not found in Dictionary on line: %d, word index: %d\n", spellCheckWord, lineCount, wordCount); //print word and line not in dictionary
}
rewind(fpDict); //resets dictionarry file pointer
isWordfound = 0; //resets wordfound for next iteration
}
}
fclose(fpDict);
fclose(fpWords);
return 0;
}
哇谢谢大家快速回复。你们是伟大的,月亮与那个!
答案 0 :(得分:5)
在fgets()
来电后立即删除'\ n':
while ( fgets ( line, sizeof line, fpWords ) != NULL )
{
size_t linelen = strlen(line);
assert((linelen > 0) && "this can happen only when file is binary");
if (line[linelen - 1] == '\n') line[--linelen] = 0; /* remove trailing '\n' and update linelen */
答案 1 :(得分:2)
尝试将\ n添加到您传递给strtok的参数。
答案 2 :(得分:1)
如果您只是想为了比较而删除该字符,并且知道它将在一行的末尾,那么当您将该单词读入缓冲区时,请为{{1}执行strchr()
然后,如果找到,请用\n
替换该位置。
答案 3 :(得分:1)
怎么样:
size_t length = strlen(dictionaryWord);
if (length > 0 && dictionaryWord[length-1] == '\n') {
dictionaryWord[length-1] = 0;
}