c语言从键盘获取 gets,如何使用C从键盘读取字符串?

从不知道长度的任何文件(包括stdin)读取输入时,通常最好使用getline而不是NULL或fgets,因为getline将自动处理字符串的内存分配,只要您提供一个空指针来接收 输入的字符串。 此示例将说明:

#include

#include

int main (int argc, char *argv[]) {

char *line = NULL; /* forces getline to allocate with malloc */

size_t len = 0; /* ignored when line = NULL */

ssize_t read;

printf ("\nEnter string below [ctrl + d] to quit\n");

while ((read = getline(&line, &len, stdin)) != -1) {

if (read > 0)

printf ("\n read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

printf ("Enter string below [ctrl + d] to quit\n");

}

free (line); /* free memory allocated by getline */

return 0;

}

相关部分为:

char *line = NULL; /* forces getline to allocate with malloc */

size_t len = 0; /* ignored when line = NULL */

/* snip */

read = getline (&line, &len, stdin);

将getline设置为NULL会导致getline自动分配内存。 输出示例:

$ ./getline_example

Enter string below [ctrl + d] to quit

A short string to test getline!

read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit

A little bit longer string to show that getline will allocated again without resetting line = NULL

read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

因此,使用getline,您无需猜测用户的字符串将持续多长时间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值