簡體   English   中英

C 編程:獲取行、二維數組和結束用戶輸入

[英]C programming: get line, 2D array and ending user input

char* str = NULL;
size_t capacity = 0;

getline(&str, &capacity, stdin); 
   

上述代碼是在讀取字符串輸入時使用 getline 動態分配 memory 的示例。 但是,如果我試圖將輸入讀入二維數組怎么辦?

例子:

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

我確實知道 function strlen,所以我想我可以在技術上使用它來確定何時停止讀取用戶輸入? 但我有點困惑,是否可以使用 getline 將用戶輸入讀取到 C 中的二維數組中,如所述? 我只看到有人在 C++ 中使用它

我們可以聲明一個指針數組,然后在循環中將每一行分配給二維數組。 請看下面的代碼:

#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;
}

output 是(輸入前 5 行):

krishna
rachita
teja 
sindhu
sagarika

The strings are 
krishna
rachita
teja 
sindhu
sagarika

每次使用characters = getline(&str,...)時,都會在地址str分配新的動態 memory,大小等於讀取的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);
}

示例 output:

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM