read length of string from stdin [duplicate]

2019-03-30 18:22发布

This question already has an answer here:

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

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 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

can you please give me the working code?

标签: c stdin
7条回答
何必那么认真
2楼-- · 2019-03-30 18:49

Do not use scanf, use fgets, which prevents too many characters from being read in.

char tmp[256]={0x0};
while(fgets(tmp, sizeof(tmp), stdin)!=NULL)
{
    printf("%s", tmp);
}

fgets will return a '\n' at the end of the line, NULL when stdin closes or encounters an error.

Play with it first to see what it does. If you need to break the input line into fields you can use sscanf() on tmp, sscanf works just like scanf, but on strings.

查看更多
登录 后发表回答