读多行

时间:2014-01-28 19:08:44

标签: c stdin getc


在我的一个C项目中,我需要阅读多行。假设我希望有一些指令列表,所以输入可能看起来像这样(当然我不知道最大长度):

1. First do this...
2. After that...
...
n. Finish doing this...

我想将这些数据存储在某个地方(在文件中,...),因为之后我希望能够搜索许多类似的列表等。

我想出了当时使用循环和读取一个字符的想法,我制作了这段代码(简化了一点):

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

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

char *stream;
int i=0;

stream = (char *)malloc(sizeof(char)); 
do{
    stream = (char *)realloc(stream,(i+1)*sizeof(char)); // Reallocating memory for next character
    stream[i] = getc(stdin); // Reading from stdin

    if( i>0 && stream[i-1]=='\n' && stream[i]== '\n' ) // Stop reading after hitting ENTER twice in a row
        break;
    i++;
}while(1); // Danger of infinite cycle - might add additional condition for 'i', but for the sake of question unnecessary

printf("%s\n", stream); // Print the result
free(stream); // And finally free the memory
return 0;
}

这段代码确实有效,但在我看来,这是一个非常混乱的解决方案(用户可能希望添加更多空行'\ n'以使列表更具可读性 - 但是,在更改'if后'条件是需要多次击中ENTER。)

0 个答案:

没有答案
相关问题