我怎样才能重写我的 if-statements 来工作?

How can I rewrite my if-statements to work?

所以程序基本上应该做的是我们在命令行中输入文件名 -i input.txt -o output.txt -c (命令行参数(argc 和 argv))并且程序应该读取输入文件,计算有多少个单词,如果有 -c 它应该将所有大写字母转换为小写字母并忽略标点符号。然后统计每个单词出现的次数,并将结果输出到ouput.txt中。如果没有 -i input.txt 它应该提示用户输入并执行相同的操作,如果没有 -o output.txt 它应该在编译器中打印输出。所以我的程序不起作用的是 if(argc == 4)if(argc == 3)。我现在没有 wordOccurrences 的功能。我知道 header “count.h” 不应该像 header 但现在它有效。

主文件

#include "count.h"
#include <stdio.h>``
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include "functions.c"

int main(int argc, char **argv)
{   
    //Initialize variables
    FILE *fp; //file        
    char buffer[1000];

    char *input; //for manually entering string with -c
    input = (char*)malloc(100 * sizeof(char));

    int wordcount; // the number of words

    int *ch; //a single character
    ch = (int*)malloc(100000 * sizeof(int));

    char consoleInput[60];

    if(argc >=2)
    {       
        if(argc == 6) //if argc = 5 --> wordcount -i .txt -o .txt -c
        {       
            //for (int i=0; i<=argc; i++)
            //{ 
            // if line has -i
            if (strcmp("-i", argv[1]) == 0)
            {
                //open file on directory after -i
                fp = fopen(argv[2],"r");

                //do wordcount method
                wordcount = countForFile(fp, wordcount);

                //close file
                fclose(fp);
            }// end of first if

            // if line has -o
            if(strcmp("-o", argv[3]) == 0)
            {
                //open file on directory after -o
                fp = fopen(argv[4], "w");

                //put wordcount in file
                fprintf(fp,"%d", wordcount);
                printf("Putting output to file\n");

                //close file
                fclose(fp);
            } // end of second if

            //if line has -c
            if(strcmp("-c", argv[5]) == 0)
            {
                //open file on location 2
                fp = fopen(argv[2],"r");

                // do toLowerCase method
                toLowerCase(fp,ch);

                //open file on location 2
                fp = fopen(argv[2],"r");

                //count occurances

                printf("Well countOccurances is in process\n");

                //close file
                fclose(fp);

            } //end of third if

            //}
        }
        if (argc == 5) // if argc = 4 --> wordcount -i .txt -o .txt 
        {
            //for (int i=0; i<=argc; i++)
            //{ 
            // if line has -i
            if (strcmp("-i", argv[1]) == 0)
            {
                //open file on directory after -i
                fp = fopen(argv[2],"r");

                //do wordcount method
                wordcount = countForFile(fp, wordcount);

                //close file
                fclose(fp);
            }// end of first if

            // if line has -o
            if(strcmp("-o", argv[3]) == 0)
            {
                //open file on directory after -o
                fp = fopen(argv[4], "w");

                //put wordcount in file
                fprintf(fp,"%d", wordcount);
                printf("Putting output to file\n");

                //close file
                fclose(fp);

            } // end of second if
            //}
        }
        else if(argc == 4) // if argc = 3 -> wordcount -i txt -c; wordcount -o txt -c
        {
            //for (int i=0; i<=argc; i++)
            //{
            if(strcmp("i",argv[1]) == 0)
            {
                printf("first i if working\n"); 
                if(strcmp("i",argv[1]) == 0)
                {
                    //open file on directory after -i
                    fp = fopen(argv[2],"r");

                    //do wordcount method
                    wordcount = countForFile(fp, wordcount);

                    //close file
                    fclose(fp);
                    printf("I if working\n");
                }
                //if line has -c
                if(strcmp("-c", argv[3]) == 0)
                {
                    //open file on location 2
                    fp = fopen(argv[2],"r");

                    // do toLowerCase method
                    toLowerCase(fp,ch);

                    //open file on location 2
                    //fp = fopen(argv[2],"r");

                    //count occurances

                    printf("Well countOccurances is in process\n");

                    //close file
                    fclose(fp);

                } //end of third if
            }
            else if(strcmp("-o",argv[1]) == 0)
            {
                printf("Enter q to exit\n");
                printf("Enter text: ");
                wordcount = count(input, wordcount);

                if(strcmp("-o", argv[1]) == 0)
                {
                    //open file on directory after -o
                    fp = fopen(argv[2], "w");

                    //put wordcount in file
                    fprintf(fp,"%d", wordcount);
                    printf("Putting output to file\n");

                    //close file
                    fclose(fp);
                } // end of second if

                //if line has -c
                if(strcmp("-c", argv[3]) == 0)
                {
                    //open file on location 2
                    fp = fopen(argv[2],"r");

                    // do toLowerCase method
                    toLowerCase(fp,ch);

                    //open file on location 2
                    fp = fopen(argv[2],"r");

                    //count occurances

                    printf("Well countOccurances is in process\n");

                    //close file
                    fclose(fp);

                } //end of third if
            }
            //}
        }   

        if(argc == 3) // if argc = 2 -> wordcount -i txt; wordcount -o txt
        {
            //for (int i=0; i<=argc; i++)
            //{
            if(strcmp("i",argv[1]) == 0)
            {
                //open file on directory after -i
                fp = fopen(argv[2],"r");

                //do wordcount method
                wordcount = countForFile(fp, wordcount);

                //close file
                fclose(fp);
                printf("PLS WORK\n");
            }   
            else if(strcmp("-o", argv[1]) == 0)
            {
                printf("Enter q to exit\n");
                printf("Enter text: ");
                wordcount = count(input, wordcount);

                //open file on directory after -o
                fp = fopen(argv[2], "w");

                //put wordcount in file
                fprintf(fp,"%d", wordcount);
                printf("Putting output to file\n");

                //close file
                fclose(fp);
            } // end of second if
            //}
        }
        if(argc == 2) //wordcountMain -c
        {
            //for (int i=0; i<argc; i++)
            //{
            //converting from UpperCase to LowerCase
            if(strcmp("-c", argv[1]) == 0)
            {   
                //Get input
                printf("Enter text: ");
                fgets(input,1000,stdin);

                int i = 0;
                //Loop through input
                for( i = 0;input[i]!='[=11=]'; i++) 
                {
                    //find upperCase letters
                    if(input[i] >= 'A' && input[i] <= 'Z')
                    {
                        //overwrite to lowerCase
                        input[i] = tolower(input[i]);

                        //input[i] = input[i] +32;
                        printf("Converted upperCase to lowerCase\n");

                    }//end of if statement  

                    //ignoring punctuation  
                    if(input[i] == ',' || input[i] == '.' || input[i] == '!' || input[i] == '?' || input[i] == '"' || input[i] == ':' || input[i] ==';' || input[i] == '-')
                    {
                        input[i] = ' ';
                        printf("Converted without punctuation\n");
                    }
                } //end of for loop

                printf("%s",input);
            }
            //}
        }
    }
    else
    {
        //Get input
        printf("Enter text: ");
        //fgets(input,1000,stdin);
        wordcount = count(input, wordcount);
        printf("%s",input);
        wordcount = count(input, wordcount);
    }
    return 0;
}

count.h

# pragma once
// This file needs to know what printf is
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

//count how many words for read file
int countForFile(FILE *file, int wordcount)
{
    int ch;
    int linecount, charcount;


     // Initialize counter variables
     linecount = 0;
     wordcount = 0;
     charcount = 0;


   // If file opened successfully, then write the string to file
   if ( file )
   {
       //Repeat until End Of File character is reached. 
       while ((ch=getc(file)) != EOF) {
          // Increment character count if NOT new line or space
            if (ch != ' ' && ch != '\n') { ++charcount; }

          // Increment word count if new line or space character
           if (ch == ' ' || ch == '\n') { ++wordcount; }

          // Increment line count if new line character
           if (ch == '\n') { ++linecount; }

        }
    }
   else
    {
        printf("Failed to open the file\n");
    }
    printf("Words : %d \n", wordcount);

    getchar();
    return wordcount;
}

/*
    Hello, Bye, Hello;

    int index = 2;
    String[] words = [Hello, Bye, null];
    int [] count = [2, 1, 0,];
*/
int count(char *input, int wordcount)
{   
    wordcount = 0;
    while(scanf("%s",input) != EOF)
                {
                    if(input[0] == 'q' && strlen(input) == 1)
                        break;
                    wordcount++;

                }// end of while loop

                printf("WordCount is: %d\n", wordcount);
    getchar();
    return wordcount;
}

function.h

#include "count.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

//Check for UpperCase and turn into LowerCase for a read file
toLowerCase(FILE *fp,int *ch)
{
    //Initialize variables
    int single_character;
    int i =0;

    //if file is read
    if ( file )
    {
       //Repeat until End Of File character is reached. 
       while ((single_character=getc(fp)) != EOF)
        {
            //check every single character if it's a upperCase
            if(single_character >= 'A' && single_character <= 'Z')
            {
                //if it is overwrite it to lowerCase
                single_character = tolower(single_character); //overwrite
            }   
            ch[i] = single_character;
            i++;
        } //end while   
    } //end if

   //if file not opened 
   else
    {
     printf("Error: File not opened\n");  
    } //end else    

    getchar();

    printf("toLowerCase Working\n");

} // end toLowerCase

是的,如果有任何帮助,我将不胜感激。我是 C 的新手,如果您对我应该如何使程序运行有其他想法 post 您的想法。任何事情都会有帮助。

你可以试试这个:

if(argc >= 2){
  switch(argc){
    case 3: //Some code
           break;
    case 4: //Some code
           break;
    case 5: //Some code
           break;
    //...
  }
}

我会这样做:

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


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

    char *input_file = NULL;
    char *output_file = NULL; 

    unsigned int threshold = 0;

    unsigned int wordcount = 0;

    int c;

    while(1) {
        static struct option long_options[] = {
            {"input_file", required_argument, 0, 'i'},
            {"output_file", required_argument, 0, 'o'},
            {"threshold", required_argument, 0, 'c'},
            {0, 0, 0, 0}
        };
        /* getopt_long stores the option index here. */
        int option_index = 0;

        c = getopt_long (argc, argv, "iot",
                         long_options, &option_index);

        // Detect the end of the options

        if(c == -1)
            break;

        switch(c) {
            case 'i':
                input_file = optarg;
                break;
            case 'o':
                output_file = optarg;
                break;
            case 'c':
                threshold = atoi(optarg);
                break;
            case '?':
                /* getopt_long already printed an error message. */
                break;

            default:
                abort ();           
        }



    }

    if (input_file == NULL || output_file == NULL || threshold == 0) {
        fprintf(stderr, "ERROR, Usage: %s -input_file=<fileName> -output_file=fileName -threshold=<value>\n", argv[0]);
        return 1;
    }

    // NOW input_files, outpuf_files and threshold contain the wanted values
    // The real algorithm begins


    FILE *fp = fopen(input_file, "r");

    //calculate filesize (limits the size of file to s32 bytes)
    unsigned int fileSize = 0;
    fseek(fp, 0L, SEEK_END);
    fileSize = ftell(fp);
    rewind(fp);

    char *file = malloc(fileSize * sizeof(char));

    fread(file, sizeof(char), fileSize, fp); // WARNING: ALLOCATING MEMORY FOR THE WHOLE FILE
                                             // FOR BIG FILES CONSIDER USING A BUFFER

    for (int i = 0; i < fileSize; ++i) {
        if(file[i] == ' ' || file[i] == '\n')
            wordcount++;

    }
    wordcount++; //counting last word;

    return 0;
}

在这个例子中,我使用 getopt 库来解析命令行参数(argv 数组)。这个程序应该这样调用: ./programName --input_file="filename" --output_file="filename" --threshold=value

此外,我注意到您转换了内存分配函数的 return 值。在 C 编程语言中,这 通常 被认为是不好的做法,有关详细信息,请参阅 here

我的程序不完整,不包含任何逻辑,那部分你应该尝试自己做(如果你不知道如何实现部分算法,你可以随时询问)。

我还想多说几句如何从文件中读取数据。 通常你想避免做像我所做的事情(分配一个包含整个文件的数组),因为当处理大文件时,内存需求变得过高。另一方面,您正在做相反的事情:您一次检索 1 个字节(或字符),然后立即在计算中使用它的值。这会导致您的程序在文件大小增加时变得非常慢。这是因为对文件的 I/O 操作是一项非常 time-demanding 的任务。没有 "right" 解决方案,这完全取决于情况:如果您知道文件大小不会太高(大约 10^2 MB)并且主内存 (RAM) 不是问题,那么也许你应该做一些类似于我所做的事情。如果文件大小可以变得非常大,那么您可能应该使用缓冲区(在这种特定情况下,它会使程序非常复杂)。 当文件大小变得非常大时,所有这些问题都会出现,如果您知道它们不会那么我的方法通常更快并且没有真正的禁忌症。