gpt4 book ai didi

c - 从 C 语言中读取文件并执行条件逻辑

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

我是编程新手,对如何实现这个想法有一些疑问。

我希望用户输入他们的姓名/数字字符串,如果他们的名字在列表中,则执行一串命令。我不确定如何实现这一点,但是通过一些观察,我能够想出这段代码:

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


int main(void)
{

char userName[10];

printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file

FILE *fp;

fp = fopen("results.dat", "r");

if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}

if (fp == John) {
//Dispence squence of pills for John
}

if (fp == Mary) {
//Dispence squence of pills for Mary
}



return 0;

}

我认为我没有正确使用 if 语句。我该怎么做:

if(fp == john中的内容,执行/调用另一个函数)

提前致谢!

最佳答案

试试这个:

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

int main(void)
{

char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file

FILE *fp;

fp = fopen("results.dat", "r");

if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}

while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}

return 0;

}

关于c - 从 C 语言中读取文件并执行条件逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188315/

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