【问题标题】:C programming: get line, 2D array and ending user inputC 编程:获取行、二维数组和结束用户输入
【发布时间】:2021-03-11 12:35:49
【问题描述】:
char* str = NULL;
size_t capacity = 0;

getline(&str, &capacity, stdin); 
   

上面的代码是一个在读取字符串输入时使用getline动态分配内存的例子。但是,如果我试图将输入读入二维数组呢?

例子:

Linenumberone (enter)
Linenumbertwo (enter)
(enter) <<< enter on an empty line - stop reading user input

我确实知道函数 strlen,所以我想我可以在技术上使用它来确定何时停止读取用户输入?但我有点困惑,是否可以使用 getline 将用户输入读取到 C 中的二维数组中,如所述?我只见过有人在 C++ 中使用它

【问题讨论】:

  • 要么重用字符串(getline 将根据需要重新分配它)。或者使用一个指针数组(每个指针初始化为NULL),然后依次传递给getline
  • @Someprogrammerdude 你应该把它作为答案发布

标签: arrays c string getline


【解决方案1】:

我们可以声明一个指针数组,然后在循环中将每一行分配给二维数组。请看下面的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *line[5] = {NULL}; // array of 5 pointers
    size_t len = 0;

    int i=0;

    for(i=0;i<5;i++)
    {
        getline(&line[i],&len, stdin); // reading strings
    }
    
    printf("\nThe strings are \n");
    for(int i=0; i<5; i++)
    {
        printf("%s",line[i]);  // prinitng the strings.
    }


    return 0;
}

输出是(前5行是输入):

krishna
rachita
teja 
sindhu
sagarika

The strings are 
krishna
rachita
teja 
sindhu
sagarika

【讨论】:

  • 这个答案很好,但问题是,我不知道用户将决定输入多少行,也不是特定的行数,简单应该通过输入一个结束输入空行。
  • @slipper13 mallocrealloc?
【解决方案2】:

每次使用characters = getline(&amp;str,...),都会在地址str分配新的动态内存,大小等于读取的characters的数量。在每次调用getline() 时将缓冲区地址(str 的值)存储到一个数组中就足够了。随后,getline() 中的缓冲区地址 (str) 会增加最后一个 getine() 中读取的字符数。请参阅下面的代码和示例。

#include <stdio.h>

int main () {
  char *buffer=NULL;
  size_t capacity = 0;
  size_t maxlines = 100;
  char *lines[maxlines]; // pointers into the malloc buffer for each line

  printf ("Input\n\n");

  int lines_read;
  int characters;
// read getline until empty line or maxlines
  for (lines_read = 0; lines_read < maxlines; lines_read++)  {
      printf ("Enter line %d: ", lines_read + 1);
      characters = getline (&buffer, &capacity, stdin);
// stop at empty line
      if (characters == 1) break;
// convert end of line "\n" into zero (C null-terminated string convention)
      buffer[characters - 1] = 0;
// save starting location into lines
      lines[lines_read] = buffer; // save pointer to the start of  this line in the buffer
      buffer += characters;       // set  pointer to the start of a new line in the buffer
  }

  printf ("\nOutput\n\n");

  // print lines read excluding empty line
  for (int i = 0; i < lines_read; i++)
    printf ("Line[%d] = %s\n", i+1, lines[i]);

  return (0);
}

示例输出:

Input

Enter line 1: This
Enter line 2: is
Enter line 3: an
Enter line 4: example.
Enter line 5: 

Output

Line[1] = This
Line[2] = is
Line[3] = an
Line[4] = example.

【讨论】:

    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多