我实际上没有很多代码可以在这里展示,但我似乎不能得到一个现实的答案:我如何接受来自用户的多行输入?
例如,我可能希望用户说这样的话...
name: command
command
command
command
name: command
command
command(命令的数量未知。实际上,这与行数有关。)我只是不知道从哪里开始,因为在这个问题上似乎没有太多的资源)
发布于 2012-11-10 08:44:58
伪代码:
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了,这就是我现在能做的。
发布于 2012-11-10 08:49:54
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指针数组(读者练习)。
https://stackoverflow.com/questions/13318039
复制相似问题