从标准输入读取的字符串的长度 [英] read length of string from stdin

查看:167
本文介绍了从标准输入读取的字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想借此从标准输入一个字符串,但我不想固定大小的静态数组

I want to take a string from stdin but I don't want a static array of fixed size

我知道scanf函数需要的东西在那里保存标准输入的输入,但我不能做这样的事情:

I know that scanf need something where save the stdin input, but I can't do something like this:

char string[10]
scanf("%s",string);

becouse我需要多长时间是为了分配适当的内存空间字符串之前就知道了。

becouse I need to know before how long will be the string in order to allocate the right memory space.

您能帮我解决这个问题呢?

Can you help me to resolve this problem?

woooooooo

我仍然锁定这个问题...
我要疯了。

i'm still locked with this problem... I'm going mad

您可以请您给我的工作code?

can you please give me the working code?

推荐答案

可以肯定的唯一方法是做一个循环;一次读取并存储一个字符。如果您分配的缓冲区已满,一些适量的成长吧(在同一时间超过一个字节建议性能,经典的一个规则的拇指是它的两倍)。

The only way to be sure is to do a loop; read one character at a time and store. If your allocated buffer becomes full, grow it by some suitable amount (more than one byte at a time is recommended for performance, a classic rule-of-thumb is to double it).

停止当你考虑到字符串结束,也许换行或EOF。

Stop when you consider the string to end, perhaps at line feed or EOF.

这篇关于从标准输入读取的字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆