选择有长度的线,C 过滤器

Selecting lines with length, C filter

我正在编写一个过滤器,它应该 select 所有具有指定长度的行。我最终得到了这段代码,但我不知道如何指定 n。我的意思是,n(和可选的 m)应该在命令提示符中替换为多行,但我不知道如何在代码中描述它。我想到了 case "%d",但据我所知,这样写是不可能的。这是我到目前为止的代码:

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

int main(int argc, char *argv[])
{
    int n;
    int m;
    char line[200];
    while(fgets(line,sizeof(line)/sizeof(char), stdin)!=NULL)
        {
            if(argc>1){
        switch(argv[0][0])
        {
        case 'n':
        strlen(line)==n;
        break;

        case '#n':
        strlen(line)<n;
        break;

        case 'n m':
        strlen(line)>=n && strlen(line)<=m;
        break;

        case 'n#':
        strlen(line) > n;
        break;
    }
    printf("%s\n", line);
          }}
    return 0;
}

你的帮助对我来说意义重大!我真的不知道如何让它工作了。

我认为您应该在循环之外解析命令行。假设您将要求程序的调用者在命令行上同时指定 nm,获取前两个参数并将它们转换为整数,然后循环遍历是一件简单的事情你的标准输入。像这样:

/* call this minmax.c */
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
    int n, m, len;
    char line[200];

    if (argc < 3) {
        printf("Must specify min & max line length.");
        return -1;
        }

    n = atoi(argv[1]);
    m = atoi(argv[2]);

    while(fgets(line, 200, stdin) != NULL) {
        len = strlen(line);
        if (len >=n && len <= m)
            printf(line);
        }
    return 0;
    }

假设您 运行 在 *nix:

cc -ominmax minmax.c

然后用最小和最大行长度调用它

./minmax 2 5

这将回显您键入的至少 2 个字符但不超过 5 个字符的每一行。

希望我能很好地理解您想要的程序的目的,这里是代码:

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

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

        int i=1,n,m; // n and m are the variable which holds 
                     // the limited length 
        if(argc>=3)
        {
          // you need to execute the program with this form
          // program.exe n m <file.txt
            n=atoi(argv[1]); // get the value of n
            m=atoi(argv[2]); // get the value of m
            printf("n=%d   m=%d\n",n,m);
        }
        char line[1000]; // this variable will hold each line of the file 
        while (fgets(line,sizeof(line),stdin)) // fgets used to read                                       
        {                                  //the lines in file till the newline 
            int  length=strlen(line)-1;
             // we decrement the length to get rid of 
             // the newline character
            if (length < n)
            {
                printf("line %d:%s status: < %d\n",i,line,n);
            }
            else if (length==n)
            {
                printf("line %d:%s status: = %d\n",i,line,n);
            }
            else if (length>n && length <=m)
            {
                printf("line %d:%s status: %d < <= %d\n",i,line,n,m);
            }
            else 
            {
                printf("line %d:%s status: > %d\n",i,line,m);
            }
            i++;
        }


    return 0;
}

如果代码不符合您的需求,我认为它已经足够并且可以作为对您的确切程序的支持,因为它包含您需要的一切!!希望对您有所帮助!!