我实际上并没有很多代码可以在这里显示,但我似乎无法得到一个现实的答案:我如何接受用户的多行输入?
例如,我可能希望用户说...
name: command
command
command
command
name: command
command
command
(命令的数量未知。实际上这与行数有关。)我只是不知道从哪里开始,因为这件事上似乎没有很多资源)
伪代码:
do {
read a line and put it into String variable s
Push s into an array
} while (s is not empty)
Remove the last element of the array
由于我已经好几个月没有写 C 语言了,这就是我现在可以做的。
enum { MAX_LINES = 100 };
char *lines[MAX_LINES];
int nlines;
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp) != 0 && nlines < MAX_LINES)
{
if (buffer[0] == '\n')
break;
if ((lines[nlines++] = strdup(buffer)) == 0)
...memory allocation failed...
}
命令的行在lines[0]
... lines[nlines-1]
如果您不喜欢对行数的硬连线限制,请动态分配lines
指针数组(读者练习)。