【问题标题】:c - multiple line inputc - 多行输入
【发布时间】:2012-11-10 00:38:46
【问题描述】:

我实际上并没有很多代码可以在这里显示,但我似乎无法得到一个现实的答案:我如何接收用户的多行输入?

例如,我可能希望用户说...

 name: command
       command
       command 
       command

 name: command
       command 
       command

(不知道命令的数量。实际上这确实与行数有关。)我只是不知道从哪里开始,因为这件事上似乎没有很多资源)

【问题讨论】:

    标签: c input line


    【解决方案1】:
    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 指针数组(供读者练习)。

    【讨论】:

      【解决方案2】:

      伪代码:

      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 语言了,所以我现在可以做到这一点。

      【讨论】:

        猜你喜欢
        • 2011-05-11
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 2014-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多