[英]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.