tags:

views:

180

answers:

6

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?

+2  A: 

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.

unwind
A: 

You could process the input data char by char using:

int getc(FILE *stream);

or

int getchar(void);
stacker
A: 

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.

Dacav
The array can only safely store 9 characters plus the trailing NUL '\0'.
Jonathan Leffler
Correct, but only 9 characters are read from stdin, so it's ok.
Dacav
A: 

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

David Relihan
A: 

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.

Jonathan Leffler
+1  A: 

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.

jim mcnamara