[英]c - multiple line input
我实际上没有很多代码可以在这里显示,但是我似乎无法在此上得到一个现实的答案:我该如何接受用户的多行输入?
例如,我可能希望用户说类似...
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
数组(供读者练习)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.