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条回答
Root(大扎)
2楼-- · 2019-03-30 18:34

You could process the input data char by char using:

int getc(FILE *stream);

or

int getchar(void);
查看更多
时光不老,我们不散
3楼-- · 2019-03-30 18:36

If you use fgets() then you would most likely have a '\n' character at the end in the buffer if it is sufficienly large. Some may orefer to remove it via strtok() function but it is nit safe.

I suggest the following safe way to remove that extra special character.

char *get_line (char *s, size_t n, FILE *f)
{
  char *p = fgets (s, n, f);

  if (p != NULL) strtok (s, "\n");
  return p;
}
查看更多
在下西门庆
4楼-- · 2019-03-30 18:36

You may use the following format string:

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

This forces the buffer boundaries to be respected, but requires the format string to be aware of the size of the buffer. I usually overcome this by declaring both as constants:

#define BUFSIZE 10
#define BUFFMT "%10s"

If you are working on a GNU system, you can also take advantage from the GNU extensions: the getline(3) function can avoid you a lot of headaches! Have a look here.

查看更多
别忘想泡老子
5楼-- · 2019-03-30 18:42

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

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

查看更多
三岁会撩人
6楼-- · 2019-03-30 18:44

If you don't want a static array of fixed size, the consider using a dynamically allocated array which grows as needed.

If you work on Linux or other systems with POSIX 2008 support, then you can use the (newer) getline() function. If you don't have access to such a function, consider rolling your own using the same interface.

查看更多
倾城 Initia
7楼-- · 2019-03-30 18:47

You can ensure you don't over-run your buffer like this:

   char buffer[128];
   printf("Input Text: ");
   fgets(buffer,127,stdin);

Then you just keep getting the same fixed size amount of input if you need variable size of input

查看更多
登录 后发表回答