Read string length from stdin

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

I know that scanf needs something where to save the stdin input, but I cannot do something like this:

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

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

Can you help me solve this problem?


woooooooo

I'm still blocked by this problem ... I'm going crazy

can you give me a working code?

+4
source share
7 answers

The only way to be sure is to make a loop; read one character at a time and store. If your allocated buffer is full, grow it by a suitable amount (it is recommended to use more than one byte per performance, the classic rule is to double it).

Stop if you think the line ends, perhaps in a line or EOF.

+2
source

Do not use scanf, use fgets, which prevents reading too many characters.

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

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

Play with him first to see what he is doing. If you need to split the input line into fields, you can use sscanf () for tmp, sscanf works the same as scanf, but in lines.

+2
source

If you use fgets() , then you will most likely have the character '\n' at the end of the buffer if it is large enough. Some of them can remove it with the strtok() , but it is safe.

I suggest the following safe way to remove this 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; } 
+2
source

You can process char input to char using:

 int getc(FILE *stream); 

or

 int getchar(void); 
0
source

You can 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 know the size of the buffer. I usually get over this by declaring both to be constants:

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

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

0
source

You can make sure that you do not overload your buffer as follows:

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

Then you just keep getting the same input size if you need a variable input size

0
source

If you do not want a static array of fixed size, consider using a dynamically allocated array that grows as needed.

If you are running Linux or other systems supporting POSIX 2008, you can use the (newer) getline() function. If you do not have access to such a function, consider copying your own using the same interface.

0
source

Source: https://habr.com/ru/post/1311282/


All Articles