Beginner C/C++

Moderators: None (Apply to moderate this forum)
Number of threads: 5428
Number of posts: 16949

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
string size according to user's input Posted by dona jain on 9 Aug 2007 at 3:35 AM

How to initialize a string.. so that it can hold any size..

char str[100] i dont want to do this way...str[] should be able to support as many characters as input by user..
Report
Re: string size according to user's input Posted by stober on 9 Aug 2007 at 3:14 PM
:
: How to initialize a string.. so that it can hold any size..
:
: char str[100] i dont want to do this way...str[] should be able to
: support as many characters as input by user..
:

depends -- is this a c or c++ program? in c++ you can use std::string class which expands as needed. In C you have to use pointer and initialially malloc() it to fixed length, then expand it as needed using realloc(). Don't normally have to be concerned if the string is a little larger than required -- to speed your program up a tiny bit don't call realloc() to allocate just a single character, but call it to allocate a block of characters. For example:
char *buffer = 0;
long bufsize = 0;
const int BLOCKSIZE 36;
char key;
int keycount = 0;
while( (key = getchar()) != EOF)
{
   if( (keycount+1) >= bufsize)
   {
       bufsize += BLOCKSIZE;
       buffer = realloc(bufsize);
   }
   buffer[keycount] = key;
   keycount++;
}

=============================================
never lie -- the government doesn't like the competition. (Author unknown)



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.