在我的一个 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 键)。