gpt4 book ai didi

C 代码,似乎跳过了 if 语句

转载 作者:行者123 更新时间:2023-12-02 05:21:53 30 4
gpt4 key购买 nike

首先,我并没有要求任何人为我编写程序或为我做功课......我有一个错误,我无法弄清楚是什么原因造成的,也不知道在哪里可以修复它.

因此,我正在尝试创建一个程序,该程序将从命令行获取命令和输入文件,并根据命令选择执行以下几个功能之一:要么计算输入文件的行数,要么计算输入文件中的单词,或检查输入文件中的回文,然后将回文(如果有)与字典文件进行比较。

这是目前的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

void usage(char *prog_name) //usage file if input format is wrong
{
printf("Usage: %s, <-h>|<-l>|<-w>|<-p>, <filename>\n", prog_name);
exit(0);
}

void help(char *prog_name, char *filename) //help file for -h option
{
printf("Welcome to the help file\n");
printf("For number of lines, enter: <%s>, <-l>, <%s>.\n", prog_name, filename);
printf("For number of words, enter: <%s>, <-w>, <%s>.\n", prog_name, filename);
printf("To list the palindromes in alphabetical order, print the number of
palindromes, and to check them against the dictionary, enter: <%s>, <-p>, <%s>\n",
prog_name, filename);
exit(0);
}

void fatal(char *); //function for fatal errors
void *ec_malloc(unsigned int); //error-checked malloc wrapper

void linecount(char *filename) // counts the number of lines of input file
{
char *infile;
infile = (char *) ec_malloc(strlen(filename));
strcpy(infile, filename);
FILE *fp = fopen(infile, "r");

if (fp == NULL)
fatal("input file does not exist");

int ch;
int count = 0;

do {
ch = fgetc(fp);
if( ch== '\n')
count++;
}
while( ch != EOF );

printf("Total number of lines %d\n",count);
exit(0);
}

int main(int argc, char *argv[])
{
if (argc < 3) //if there aren't enough arguments, display the usage file
{
usage(argv[0]);
}
else if (argv[1] == "-h") //this is the help option
{
help(argv[0], argv[2]);
}
else if (argv[1] == "-l") //this is the line count option
{
linecount(argv[2]);
}
else
{

fatal("skipped if functions");
}
return 0;
}
void fatal(char *message) //this function displays an error message and then exits
{
char error_message[100];
strcpy(error_message, "[!!] Fatal Error ");
strncat(error_message, message, 83);
perror(error_message);
exit(-1);
}

void *ec_malloc(unsigned int size) //wrapper function for an error checked malloc
{
void *ptr;
ptr = malloc(size);

if(ptr == NULL)
fatal("in ec_malloc() on memory allocation");

return ptr;
}

所以,当我运行时:

gcc -o fr filereader.c

./fr -h fevbwervrwe.txt

我收到错误消息,指出已跳过 if 语句。

如果我试着运行也是一样

./fr -l vrweqvervvq.txt

编译器似乎跳过了我的 if 语句,老实说我不明白为什么。任何帮助都将不胜感激。

最佳答案

尝试使用 strcmp() 而不是 ==

关于C 代码,似乎跳过了 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7640740/

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