c - How can I compare user input to string stored into file?
问题描述
I gotta write a file-handing code which will compare the string received from the user to a string of char stored into a file in C. I've trying since yesterday. I have no clue on how to do that. I tried many things, but nothing seems to work.
//
// 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;
}
My problem is... the space between every word of the string in the file, because I have to check if there's another word starting, for instance... (Hi Hi)... I thought about using something like this in my code but I did not work as well.
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) != EOF
是一样的,c = (fgetc(file) != EOF)
这显然不是你想要的。它应该是(c = fgetc(file)) != EOF
其次,上面的语句(假设你没有得到 EOF)实际上读取了一个字符。所以 if 语句应该是if(c != ' ')
三、c
需要声明为int
推荐阅读
- streamreader - C# FileSystemWatcher & StreamReader 给出“文件正在被另一个进程使用”错误
- azure - Terraform 数据块实验室提供商
- node.js - 为什么我得到 Req.Req (嵌套请求)这个配置在 express 中?
- javascript - React:将数据转换为高级形式(或如何在 react chartjs 2 的图表中处理我的数据)
- oracle-apex - 如何从 SQL Developer 中清除 Apex Oracle 调试历史记录?
- firebase-realtime-database - Firebase 实时数据库规则来过滤列表
- php - php redis会话保存处理程序扩展函数gc(垃圾收集)
- ios - 运行 react-native run ios 时如何配置运行哪个 xcodebuild 工具版本?
- python - 不能腌制 _thread.RLock 对象 - 我看不到问题
- reactjs - React Material UI手风琴:手风琴打开时如何调用函数?