[prog] Strings in C

Therese Gustafsson th_gustafsson at yahoo.com
Fri Oct 18 12:53:36 EST 2002


--- Diggy Bell <diggy at dbsoftdev.com> wrote:
> A couple of quick C topics...
> 
> 1. Strings are represented in C as an array of
> characters terminated with
> '\0'.  This means that for any string that you use,
> you will need to account
> for an additional character.  If you want to allow
> 10 characters, you would
> define the string as follows:
> 
>     char myString[11];
> 
> The value "TESTING123" would be stored as:
> 
> T, E, S, T, I, N, G, 1, 2, 3, \0
> 
> 2. Reading user input from stdin doesn't provide a
> great deal of control.
> If this were a production application, fgets
> wouldn't be the best option,
> but that probably isn't a concern here.  

Could you explain this a bit more? I've never really
understod how you're supposed to read user input in a
good way. I would really like to learn a better way! 

>But, since
> you're using fgets, you
> might want to use it to limit the number of
> characters a bit.  The fgets()
> call will also properly \0 terminate your string.
> 
>     char email[41]; // the final variable for the
> email address (include 1
> character for the \0)
>     int email_len; // the length of the string
> returned
> 
>     // print the user message
>     printf("Please enter your email address: ");
>     // make sure fgets doesn't return NULL
>     if(fgets(email, 40, stdin))
>     {
>         email_len = strlen(email); // will always be
> 40 or less
>     }

What happens here if the user writes more then 40
characters? Are those characters just skipped? If I
want to get more user input after this will they end
up there? 
 
> Voila!  You should now have a string containing the
> email address with a
> length of 40 or less.

If the string is less then 40 will the '\0' at the end
affect the database in someway? Or is it ok to insert
a string with an '\0' at the end?
 
> 3. When your ready to go to the database, it's time
> to create some SQL.
> Here's the easiest way I can think of at the moment
> (1st cup of coffee
> still...):
> 
>     char sqlstring[512]; // this string is often too
> large, but you gotta
> allow for it
> 
>     sprintf(sqlstring, "insert into mytable
> (emailaddr) values ('%s');",
> email);
> 
> The SQL string is now ready to execute against your
> PostgreSQL database.
> 
> Good luck!
> 
> William D. 'Diggy' Bell
> Principal
> DB Software Development
> http://www.dbsoftdev.com

Thanks!

/Therese

__________________________________________________
Do you Yahoo!?
Faith Hill - Exclusive Performances, Videos & More
http://faith.yahoo.com



More information about the Programming mailing list