2012-11-10 23 views
0

我其實沒有太多的代碼在這裏顯示,但我似乎無法得到一個現實的答案:我如何從用戶採取多行輸入?c - 多行輸入

例如我可能希望用戶這樣說......

name: command 
     command 
     command 
     command 

name: command 
     command 
     command 

(命令的數量是不知道。其實那個真的有行#做的。)我只是不知道從哪裏開始,因爲似乎沒有成爲對此事的許多資源)

回答

0

僞代碼:

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,這是我現在可以做。

0
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指針數組(針對讀者的練習)。