繁体   English   中英

C循环读取输入行

[英]C loop to read lines of input

我想在C中创建一个程序,它接受任意数量的任意长度的行作为输入,然后打印到控制台输入的最后一行。 例如:

输入:

hi
my name is
david

输出: david

我认为最好的方法是使用一个循环,将每一行作为输入并将其存储在char数组中,因此在循环结束时,最后一行最终存储在char数组中,我们可以打印出来。

到目前为止,我只在C中进行了一次演讲,所以我认为我只是在Java / C ++思维模式上设置错误,因为我对这些语言有更多的经验。

这是我到目前为止所得到的,但我知道它远远不够正确:

#include <stdio.h>

int main()
{
    printf("Enter some lines of strings: \n");

    char line[50];

    for(int i = 0; i < 10; i++){
        line = getline(); //I know this is inproper syntax but I want to do something like this
    }

    printf("%s",line);


}

我在循环中也有i < 10 ,因为我不知道如何找到输入中的总行数,这将是循环它的适当时间。 此外,输入正在从中一次性输入

./program < test.txt 

在Unix shell中的命令,其中test.txt有输入。

使用fgets()

while (fgets(line, sizeof line, stdin)) {
    // don't need to do anything here
}
printf("%s", line);

您不需要限制迭代次数。 在文件的末尾, fgets()返回NULL并且不修改缓冲区,因此line仍将保留读取的最后一行。

我假设您知道输入行的最大长度。

这一个肯定会为你完成这项工作

static char *getLine( char * const b , size_t bsz ) {
            return fgets(b, bsz, stdin) );
}

但是请记住fgets也会在缓冲区的末尾添加一个'\\n'字符,所以可能是这样的

static char *getLine( char * const b , size_t bsz ) {

            if( fgets(b, bsz, stdin) ){
                    /* Optional code to strip NextLine */
                    size_t size = strlen(b);
                    if( size > 0 && b[size-1] == '\n' ) {
                            b[--size] = '\0';
                    }
                    /* End of Optional Code */
                    return b;
            }
            return NULL;
    }

并且在调用getline时需要稍微更改一下代码

#define BUF_SIZE 256
char line[BUF_SIZE];

for(int i = 0; i < 10; i++){
    if( getLine(line, BUF_SIZE ) ) {
            fprintf(stdout, "line : '%s'\n", line);
    }

}

现在很有可能创建像这样的函数

char *getLine();

但是然后需要定义该函数的行为,例如,如果函数getLine()动态分配内存,那么您可能需要使用free来取消分配getLine()返回的指针

在这种情况下,功能可能看起来像

char *getLine( size_t bsz ) {
        char *b = malloc( bsz );
        if( b && fgets(b, bsz, stdin) ){
           return b;
        }
        return NULL;
}

根据你的功能有多小,你可以考虑让它成为inline想法,或许这是现在的一个小题目。

为了获得动态长度的动态输入数量,当输入的长度更长时,您必须继续重新分配缓冲区。 为了存储最后一行,你必须使用另一个指针来跟踪它并停止从终端输入你必须按下EOF键(ctrl + k)。 这应该做你的工作。

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

char *get_last_line(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str, *last_str = NULL;
    int ch;
    size_t len = 0, last_len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if(!str)return str;
    while(ch=fgetc(fp)){
        if(ch == EOF){
            break;
        }
        if(ch == '\n'){
            str[len]='\0';
            last_len = len;
            last_str = realloc(last_str,sizeof(char)*last_len);
            last_str[last_len]='\0';
            //storing the last line
            memcpy(last_str,str,sizeof(char)*last_len);
            str = realloc(NULL, sizeof(char)*size);//size is start size
            len = 0;
        }
        else {
            str[len++]=ch;
            if(len==size){
                str = realloc(str, sizeof(char)*(size+=16));
                if(!str)return str;
            }
        }
    }
    free(str);
    return last_str;
}

int main(void){
    char *m;

    printf("input strings : ");
    m = get_last_line(stdin, 10);
    printf("last string :");
    printf("%s\n", m);
    free(m);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM