gpt4 book ai didi

c - 如何将用户输入的字符串与C中文件中的字符串进行比较

转载 作者:行者123 更新时间:2023-11-30 17:44:42 25 4
gpt4 key购买 nike

所以我试图制作一个程序,在文件中搜索用户输入的单词。如果有匹配,它会说“FOUND IT”,如果找不到任何东西,它会说“COULDNT FIND ANYTHING”(显然:p)。我不清楚如何扫描文件中用户选择的单词(通过 scanf 写入)。

这是我的(非功能性)代码。感谢您的任何建议!

#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <string.h>
#include <string>
#define slovo 255

using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i;
char secret[slovo];
int outexists,fileexists;
system("Color 02");

setlocale(LC_ALL, "");
FILE*out = fopen("additions.txt", "w+");
if (!out)
{
perror("additions.txt");
getchar();
return 1;

}
else
{
outexists = 1;
}
FILE*file = fopen("db.txt", "r");

if (!file)
{

perror("db.txt");
getchar();
return 1;

}
else
{
fileexists = 1;
}
char artist[slovo];

printf("Welcome, hit ENTER to start looking.\n");
getchar();
printf("Please enter for the word you wish to search for in our database !
\n ");

scanf("%s",&artist);



**/* THIS PART */** if (fileexists == 1 && outexists == 1)
{
while (fscanf(file, "%c", secret) != EOF){

{ if (!strncmp(secret, artist, sizeof(artist)))
{
printf("FOUND IT \n");
fclose(file);
}
else
{
printf("COULDNT FIND IT \n");
fclose(file);

}
}

}


}







printf("Which word do you wish to add ?\n");
scanf("%s", artist);
fprintf(out, "%s", artist);
printf("done! \n");
getchar();




fclose(file);
fclose(out);


getchar();



return 0;

}

最佳答案

您可能需要转换模式 %s而不是%c ,后者只读取一个字符。前者读取一个字符串。

fscanf(file, "%s", secret)

编辑

刚刚也看到了,

fclose(file);

您关闭 if 中的文件和 else在 while 循环内仅经过一个 fscanf + strncmp 。不要这样做,请在 wile 循环终止后关闭文件。

也只需使用 strcmp而不是strncmp .

编辑2

因此,在复制粘贴“棘手”代码(顺便说一句,将我的控制台字体颜色变成绿色)之后,我能够在文本文件中找到一个单词:

首先摆脱那个getchar(); !

printf("Welcome, hit ENTER to start looking.\n");
getchar();

我总是在 Welcome, hit ENTER to start looking. 之后输入要搜索的键打印出来,当按 Enter 键时,不会读取任何内容,因为 getchar()正在等待输入。

第二个

scanf("%s",&artist);

不正确,请使用

scanf("%s", artist);

相反,不需要传递地址,它已经是一个数组了!

printf("Welcome, hit ENTER to start looking.\n");
printf("Please enter for the word you wish to search for in our database !\n");
scanf("%s",artist);
if (fileexists == 1 && outexists == 1) {
char found = 0;
while (fscanf(file, "%s", secret) != EOF) {
if (!strcmp(secret, artist)) {
found = 1;
break;
}
}
fclose(file);
if(found) {
printf("FOUND IT \n");
} else {
printf("COULDNT FIND IT\n");
}
}

关于c - 如何将用户输入的字符串与C中文件中的字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19882469/

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