gpt4 book ai didi

c - C中\n字符的诅咒

转载 作者:太空宇宙 更新时间:2023-11-04 00:26:33 25 4
gpt4 key购买 nike

我制作了一个简单的拼写检查程序,它读取字典和用户文本文件以进行检查。该程序需要显示任何不在词典中的单词的行和单词索引。因此它可以正常工作,直到用户文本文件中有返回 \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;
}

哇,感谢大家的快速回复。你们太棒了,太棒了!

最佳答案

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 */

关于c - C中\n字符的诅咒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8621175/

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