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++中使用它
发布于 2020-11-29 19:27:04
我们可以声明一个指针数组,然后在循环中将每一行赋给2D数组。请参见以下代码:
#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发布于 2020-11-29 21:55:56
每次使用characters = getline(&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.https://stackoverflow.com/questions/65059165
复制相似问题