首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C编程:获取行、二维数组和结束用户输入

C编程:获取行、二维数组和结束用户输入
EN

Stack Overflow用户
提问于 2020-11-29 18:34:38
回答 2查看 332关注 0票数 0
代码语言:javascript
复制
char* str = NULL;
size_t capacity = 0;

getline(&str, &capacity, stdin); 

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

示例:

代码语言:javascript
复制
Linenumberone (enter)
Linenumbertwo (enter)
(enter) <<< enter on an empty line - stop reading user input

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

EN

回答 2

Stack Overflow用户

发布于 2020-11-29 19:27:04

我们可以声明一个指针数组,然后在循环中将每一行赋给2D数组。请参见以下代码:

代码语言:javascript
复制
#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行):

代码语言:javascript
复制
krishna
rachita
teja 
sindhu
sagarika

The strings are 
krishna
rachita
teja 
sindhu
sagarika
票数 0
EN

Stack Overflow用户

发布于 2020-11-29 21:55:56

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

代码语言:javascript
复制
#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);
}

输出示例:

代码语言:javascript
复制
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.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65059165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档