[prog] Strings in C

Therese Gustafsson th_gustafsson at yahoo.com
Fri Oct 18 02:02:19 EST 2002


Hi!

I'm trying to write a C-program that accesses a
postgresql-database. I'm having trouble with the
stringhandling and I'm hoping someone here can help
me. 

I have a short code-example and I'm going to try to
explain what my problem is.

Here are my variables:
char email[256],l_email[40];
int email_length;

This is where the user input is read in.
printf("Input email-address: ");
fgets(email, 256, stdin);

Now here comes my problem. The email field in the
database is only 40 characters long, so now I want to
make sure that the email string is max 40 characters
long and I don't want the "\0"-character at the end of
the string.

Here's what I've done. I get the length of the string
the user input with strlen. (I don't understand why I
have to subtract one, but if I don't the stringlength
is one character to long. I thought strlen didn't
count the "\0"-character?) Then if the length of the
user input is longer than the field in the database I
just truncate it.
email_length = strlen(email)-1;
if (email_length > 40)
{
        email_length = 40;                          
}

Now I copy the user input to another string that's as
long as the field in the database. This is to copy all
user input except for the "\0".	
strncpy(l_email,email,email_length);

Problem number 1: If the string the user wrote is less
then 40 characters the end of the l_email string
sometimes contains "junk"-characters. How can I get
rid of those? I want the rest of the string empty.

Problem number 2: Isn't there an easier way to do
this? It seems as if I've made it to complicated.

I'm sorry if I haven't explained it so you can
understand. English isn't my first language. 

/Therese

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



More information about the Programming mailing list