gpt4 book ai didi

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

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

我必须编写一个文件处理代码,它将将从用户接收到的字符串与存储在 C 文件中的字符字符串进行比较。我从昨天开始就一直在尝试。我不知道该怎么做。我尝试了很多方法,但似乎没有任何效果。

//
// 2.c
// IFTM Exercises
//
// Created by Lelre Ferreira on 10/27/19.
// Copyright © 2019 Lelre Ferreira. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, const char * argv[]){

FILE *file = fopen("file.txt", "w");
char text[] = "hi hi hi hi hi hi"; //string to be allocated into the file
char c, userInput[] = "hi"; // simulates the user input
int i = 0, count = 0;



if (file == NULL) {
printf("Failure to create file.\n");
exit(1);
} else {
for (i = 0; i < strlen(text); i++) {
printf("Inserting: [%c]\n", text[i]);
fputc(text[i], file);
}
printf("All done.\n");
}
fclose(file);


fopen("file.txt", "r");
while ((c = fgetc(file) != EOF)){
fscanf(file, "%s", text);
if (strcmp(userInput, text) == 0) {
count++;
}
}
fclose(file);



printf("Many times present: %d\n", count);
return 0;
}

我的问题是...文件中字符串的每个单词之间的空格,因为我必须检查是否有另一个单词开头,例如...(嗨嗨)...我考虑过使用类似的东西这在我的代码中,但我的效果不佳。

while ((c = fgetc(file) != EOF)){ // While the end of the file does not happen keep running.
if ((c = fgetc(file) != ' ')) { //If an blank space is found... I does not make any sense actually. I'm desesperated.
strcmp(userInput, text){
count++
}
}
}

最佳答案

while ((c = fgetc(file) != EOF)){ 
if ((c = fgetc(file) != ' ')) {
strcmp(userInput, text){
count++
}
}
}

这里存在三个主要问题。

首先, c = fgetc(file) != EOFc = (fgetc(file) != EOF) 相同,这显然不是你想要的。它应该是 (c = fgetc(file)) != EOF

其次,上面的语句(假设您没有得到 EOF)实际上读取了一个字符。所以 if 语句应该是 if(c != ' ')

第三,c需要声明为int

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

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