Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1) 
Author Message
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

Here is my code,  It uses some C++ because the fgets I was using made
the program lock up when it was run.  I would like to remove all of
the C++ code and make it just a C program since that is what I am
learnign right now.  I am trying to put information into a struct and
view the info in the struct.  I just get junk when I try to view the
contence of the struct.  Any help with this would be apriceated.
        Here is a list of the code and I have attached it also.

/*************************************************
 *      This program will take a list of names   *
 * and addresses and arange them for printing    *
 * lables.                                       *
 *************************************************/

#include    <stdio.h>
#include          <stdlib.h>
#include                <iostream.h>

struct box  {
  char      name[50];         /*persons name*/
  char      address[50];      /*persons address*/
  char      city[50];         /*I think these are rather self
evadent*/
  char      state[2];
  char      zip[5];

Quote:
};

#define max_names 100
struct box addresses[max_names];   /* The struct aray to stor the
names and addresses */

char    name[50],address[50], city[50], state[2], zip[5];     /*
Varibles for temp storage */
int     counter = 0, counte, size[5], counting, cnt;
char    option[2], con;                                        /* Used
to control what function you are in. */
main()
  {

  while (1)
    {
    counter++;                                                    /*
Ask what the person */
    (void)printf("Please select an option\n");                  /*
*/
    (void)printf("\n");                                        /*
wants to do.        */
    (void)printf("E:  Enter an new name and address.\n");       /*
*/
    (void)printf("V:  View names in list.\n");                 /*
*/
    (void)printf("Q:  Quit.\n");                              /*
*/
    (void)printf("\n");                                        /*
*/
    (void)printf("Selection:");                                /*
*/
    cin>>option;

    switch(option[0]) {             /* figure what the user chose */

      case 'q':
      case 'Q':

          exit(0);

      case 'e':
      case 'E':

          (void)printf("Please enter the persons name:");           /*
Get the name and address to be added to the list */
          cin >> name;
          (void)printf("Please enter the persons street address:");
          cin >> address;
          (void)printf("Please enter the persons city:");
          cin >> city;
          (void)printf("Please enter the persons state:");
          cin >> state;
          (void)printf("Please enter the persons zip:");
          cin >> zip;
          counte = 0;
          while (counte <= 50)
                        {
                        addresses[counter].name[counte] =
name[counte];
                                addresses[counter].address[counte] =
address[counte];
                                addresses[counter].city[counte] =
city[counte];
                                addresses[counter].state[counte] =
state[counte];
                                addresses[counter].zip[counte] =
zip[counte];       /* Stor the name and address */
                        counte++;
                        }
          (void)printf("Record entered.\n");

          continue;

      case 'v':
      case 'V':

          counting =0;
          while (1)            /* loop till user is done. */
                {
                for (cnt=0; cnt <=
sizeof(addresses[counting].name[cnt]); cnt++)  /* read the info out ot
the struct aray */
                        {
                (void)printf("Name: %c", addresses[0].name[cnt]);
                    }
                (void)printf("Address: %c\n",
addresses[counting].address);
                (void)printf("City: %c\n", addresses[counting].city);
                (void)printf("State: %c\n",
addresses[counting].state);
                (void)printf("zip: %c\n", addresses[counting].zip);
                (void)printf("Enter Q to quit or C to continue
listing.\n");
                cin >> con;
                if ((con == 'q') || (con == 'Q'))            /* ask
the user if they want to continue or quit */
                        {
                        break;
                    }
                counting++;
            }
          continue;
      }
    }
    return (0);
  }



Wed, 03 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

Whew!!  I think the first thing to note is "What isn't wrong with
it??"  You never said what didn't work.  Instead of fgets() you might
simply try gets().  fgets requires a stream argument.  gets() assumes
standard input.  

I had to clean up some of this, probably because newsreaders aren't
always that great at formatting properly.    Sorry if I messed up
anything you really intended.

I recommend that you try to train yourself to break your code down
into functions.   By converting your option menu, your data input and
your display segments into separate functions and encapsulating calls
to them inside of a controlling loop you make your intentions a bit
more understandable.  It's hard to understand what's going on in a
switch if the case statements are spread out due to lots of code
between them.  Unless the code is short, use case statements to call
user defined functions.  The way you have it written the data is
globally accessible anyway so separate functions can access the
structures.

Learn the functions in string.h to handle your strings.  

Test each portion of the program as you develop it.  Don't try to
write the entire program and then get it to work.  Don't be afraid to
put debugging code in and remove it when you get the functionality
working right.  You might test your input immediately after you get it
to make sure its correct before you try to store it where it counts.

Quote:

>Here is my code,  It uses some C++ because the fgets I was using made
>the program lock up when it was run.  I would like to remove all of
>the C++ code and make it just a C program since that is what I am
>learnign right now.  I am trying to put information into a struct and
>view the info in the struct.  I just get junk when I try to view the
>contence of the struct.  Any help with this would be apriceated.
>    Here is a list of the code and I have attached it also.
>/*************************************************
> *      This program will take a list of names   *
> * and addresses and arange them for printing    *
> * lables.                                       *
> *************************************************/
>#include  <stdio.h>
>#include  <stdlib.h>
>#include  <iostream.h>
>struct box  {
>  char      name[50];         /*persons name*/
>  char      address[50];      /*persons address*/
>  char      city[50];         /*I think these are rather self evident*/
>  char      state[2];
>  char      zip[5];
>};
>#define max_names 100
>struct box addresses[max_names];   /* The struct array to store the names and addresses */
>char    name[50],address[50], city[50], state[2], zip[5];     /* Varibles for temp storage */
>int     counter = 0, counte, size[5], counting, cnt;
>char    option[2], con;   /* Used to control what function you are in. */
>main()
>{
>  while (1)
>    {
>    counter++;                                                    /*Ask what the person */
>    (void)printf("Please select an option\n");                  /*  */
>    (void)printf("\n");                                        /* wants to do.  */
>    (void)printf("E:  Enter an new name and address.\n");       /* */
>    (void)printf("V:  View names in list.\n");                 /* */
>    (void)printf("Q:  Quit.\n");                              /* */
>    (void)printf("\n");                                        /* */

  You could avoid a second statement by putting this newline after the
other one in the preceding printf() statement.

Quote:
>    (void)printf("Selection:");                                /* */
>    cin>>option;

I question what all the empty comments are for.
You don't need the (void) in front of your functions calls.
You could get by making 'option' a char instead of a char array so you
don't have to access the character by subscripting the array in your
switch statement.  But see the caveat on inputing a char for your
option and what buffering can do to you later in my comments.  If
you're trying to stick with C and avoid the C++, try using getch().
It doesn't require the input of a newline to tell the program to
accept the keyboard data.

Quote:
>    switch(option[0]) {             /* figure what the user chose */
>      case 'q':
>      case 'Q':
>          exit(0);
>      case 'e':
>      case 'E':
>          (void)printf("Please enter the persons name:");          
>                /*Get the name and address to be added to the list */
>          cin >> name;

Don't use cin in this manner if you're expecting more than a first
name.  cin will only input up to the first whitespace character it
encounters.  Best to use   cin.getline(name, 49);  .  That applies to
most of your input statements below.

Quote:
>          (void)printf("Please enter the persons street address:");
>          cin >> address;
>          (void)printf("Please enter the persons city:");
>          cin >> city;
>          (void)printf("Please enter the persons state:");
>          cin >> state;

Major common mistake.  Two actually.  You're only reserving space for
two characters when a two character state needs three bytes to hold
the two characters and the nul terminator.  You also can't depend on
your user to only put in two characters.  After all, you didn't tell
them to limit it to two and even if you did, when was the last time a
user listened to you anyway.   The same aplies to your zip code field
below.  There are some 9/10 character zip code fields out there.
Expand your input array and test for the input length before you do
anything else with it.  If you leave it at two chars and that's all
that gets put in, the input of the zip field will likely overwrite the
nul terminator that flows over into its storage space.

Quote:
>          (void)printf("Please enter the persons zip:");
>          cin >> zip;
>          counte = 0;
>          while (counter <= 50)
>    {
>            addresses[counter].name[counte] = name[counte];
>    addresses[counter].address[counte] = address[counte];
>    addresses[counter].city[counte] = city[counte];
>    addresses[counter].state[counte] = state[counte];

Rather perverse way of copying one field into another but it works.
Except......state and zip are not 50 characters wide like the rest of
the fields.  You're probably copying garbage into other fields this
way.    Use something like

strcpy (addresses[counter].name, name);

Also, you incremented counter at the beginning of the loop which means
that the program automatically points to the second record in your
array and your test to end the input may cause you to overflow the
back end of the array.

Quote:
>    addresses[counter].zip[counte] = zip[counte];       /* Stor the name and address */
>            counte++;
>            }
>          (void)printf("Record entered.\n");
>          continue;

Recommend using break to bust out of a switch and let the loop take
care of going back to the beginning.

Quote:
>      case 'v':
>      case 'V':

>          counting =0;
>          while (1)            /* loop till user is done. */
>            {
>            for (cnt=0; cnt <= sizeof(addresses[counting].name[cnt]); cnt++)  

Ohhh, bad use of sizeof.  sizeof applies to the data type which, if
this part even compiles, would probably give you a value of 1 since
you're applying it to a character in an array within the structure.
You need to use strlen() to get the length of an existing string.  But
why bother when.....

Quote:
>                 /* read the info out ot the struct aray */
>                    {
>            (void)printf("Name: %c", addresses[0].name[cnt]);

.....you can print this by doing
     printf ("Name: %s\n", addresses[0].name);
You also never output a newline and are only referencing the first (0
index) of the array which you've never put anything in because you
incremented counter past that before you got any input.  Shouldn't you
be indexing with 'counting' as you did for the other fields below?

Quote:
>                }
>            (void)printf("Address: %c\n", addresses[counting].address);

Use %s to print strings.  Don't know why you did this this way and
used a loop for the name.  address refers to the address of the array
named address within your structure.  %c is trying to interpret an
address as a character.  Ditto for all the following.

Quote:
>            (void)printf("City: %c\n", addresses[counting].city);
>            (void)printf("State: %c\n", addresses[counting].state);
>            (void)printf("zip: %c\n", addresses[counting].zip);
>            (void)printf("Enter Q to quit or C to continue listing.\n");
>            cin >> con;
>            if ((con == 'q') || (con == 'Q'))            /* ask the user if they want to continue or quit */

Not an error, but you switched tactics compared to how you handled
getting 'option'.  Doing this will read in the one character but will
leave the newline in the input queue, which can mess up your attempt
to read in option or some other input following.  You might end up
with an empty string.

Quote:
>                    {
>                    break;
>                }
>            counting++;
>            }
>          continue;

A continue at the end of a loop is superfluous.  It's going to go back
to the top of the loop anyway.

Quote:
>      }
>    }
>    return (0);
>  }


Senior Network Systems Programmer
Postmaster, Cook, Bottle Washer


Fri, 05 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

Quote:

>Here is my code,  It uses some C++ because the fgets I was using made
>the program lock up when it was run.  I would like to remove all of
>the C++ code and make it just a C program since that is what I am
>learnign right now.  I am trying to put information into a struct and
>view the info in the struct.  I just get junk when I try to view the
>contence of the struct.  Any help with this would be apriceated.
>    Here is a list of the code and I have attached it also.

/*************************************************
 *      This program will take a list of names   *
 * and addresses and arrange them for printing   *
 * labels [will it?].                            *
 *************************************************/

#include    <stdio.h>
#include    <stdlib.h>

struct box  {
  char      name[50];
  char      address[50];
  char      city[50];
  char      state[2];
  char      zip[5];

Quote:
};

#define max_names 100

struct box addresses[max_names];  

int main(void)
{
   /* declare local variables locally */
   int i, counter=0;
   char    option[2];                                        

   while (1) {
    (void)printf("Please select an option\n\n");
    (void)printf("E:  Enter an new name and address.\n");      
    (void)printf("V:  View names in list.\n");                
    (void)printf("Q:  Quit.\n");                              
    (void)printf("\n");                                      
    (void)printf("Selection:");                              
    fgets(option, 2, stdin);

    switch(option[0]) {             /* figure what the user chose */

      case 'q':
      case 'Q':

          exit(0);

      case 'e':
      case 'E':

          /* if it's possible to store the data where
             it should go right away, don't move it
             around first */
          (void)printf("Please enter the persons name:");          
          fgets(adresses[counter].name,
                sizeof adresses[counter].name,
                stdin);
          (void)printf("Please enter the persons street address:");
          fgets(adresses[counter].address,
                sizeof adresses[counter].address,
                stdin);
          (void)printf("Please enter the persons city:");
          fgets(adresses[counter].city,
                sizeof adresses[counter].city,
                stdin);
          (void)printf("Please enter the persons state:");
          fgets(adresses[counter].state,
                sizeof adresses[counter].state,
                stdin);
          (void)printf("Please enter the persons zip:");
          fgets(adresses[counter].zip,
                sizeof adresses[counter].zip,
                stdin);

          (void)printf("Record entered.\n");
          counter++;
          /* now what do you want to do when counter >= max_names?? */
          /* I'd suggest falling through and quitting */
          if(counter < max_names)
                break;
          /* fall through */

      case 'v':
      case 'V':

          for(i=0; i<counter; i++)    /* loop till user is done. */
                {
                char c='C';

                /* printf() provides the %s format, very convenient
                   for printing whole strings one at a time */
                (void)printf("Name: %s\n", addresses[i].name);
                (void)printf("Address: %s\n", addresses[i].address);
                (void)printf("City: %s\n", addresses[i].city);
                (void)printf("State: %s\n", addresses[i].state);
                (void)printf("zip: %s\n\n", addresses[i].zip);
                printf("Enter Q to quit or %c to continue listing.\n",
c);
                fgets(option, 2, stdin);
                if ((option[0] == 'q') || (option[0] == 'Q'))
                     break;
                /* flexible user interface */
                c=toupper(option[0]);
                }

          if(counter < max_names)
                  break;
          else    exit(0);

      }
  }
  return (0);

Quote:
}

==
Miguel Carrasquer Vidal                     ~ ~
Amsterdam                   _____________  ~ ~

========================== Ce .sig n'est pas une .cig



Fri, 05 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

Quote:

> Whew!!  I think the first thing to note is "What isn't wrong with
> it??"  You never said what didn't work.  Instead of fgets() you might
> simply try gets().  fgets requires a stream argument.  gets() assumes
> standard input.  

no.  gets() is a huge risk to the stability of your program and
security of your computer.  gets() can write data write data right of
into the sunset as long as the user keeps typing, whether the space
for that data was actually allocated or not.  the users input could be
overwriting parts of the programs code or other data, even system
data.

fgets() is much more reliable since you can specify a maximum length for
the input. to call fgets() to work similarly to gets() just call it with
stdin:  fgets(str,length,stdin);

the string returned will have an extra newline that gets() doesn't
return, so you can get rid of that with: strtok(str,"\n");

gets() is easier at first, but can cause some real problems.  it is
best to stay way from that pitfall from the beginning.
--
____________________}John Flinchbaugh{______________________


~~~~~~~~~~~~microsoftfree==100%linux==100%power~~~~~~~~~~~~~



Mon, 08 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

Quote:

> fgets() is much more reliable since you can specify a maximum length for
> the input. to call fgets() to work similarly to gets() just call it with
> stdin:  fgets(str,length,stdin);

> the string returned will have an extra newline that gets() doesn't
> return, so you can get rid of that with: strtok(str,"\n");

How are you going to use strtok to remove the newline character?

Wouldn't it be better to use strchr as in

#include <stdio.h>
#include <string.h>

int main()
{
   char name[50],*s;

   printf("Your name is ?: ");
   fgets(name,50,stdin);
   s = strchr(name,'\n');
   if(s)
      *s = '\0';
   printf("You enter %s as your name.",name); /* Prints as one line */  
   return 0;

Quote:
}:

--
Al Bowers
Tampa, FL

http:www.gate.net/~abowers/index.html


Fri, 12 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

[Someone's news software is screwed up.  The quoted article has just been
 filed for approval, but I had *not* sent it out when I got this followup.
 You can tell because the "In-Reply-To:" header refers to an article that was
 not sent to the group by the moderator.  *sigh*.
 -mod]

Quote:

> How are you going to use strtok to remove the newline character?

> Wouldn't it be better to use strchr as in

> #include <stdio.h>
> #include <string.h>

> int main()
> {
>    char name[50],*s;

>    printf("Your name is ?: ");
>    fgets(name,50,stdin);
>    s = strchr(name,'\n');
>    if(s)
>       *s = '\0';
>    printf("You enter %s as your name.",name); /* Prints as one line */  
>    return 0;
> }:

you call strtok with the string to tokenize and a string of delimiters.
strtok then changes the string you passed it to the first token,
EXCLUDING the delimiter (in our case the '\n').  if the delimiter
isn't present, the string just stays as it was.

give it a try.  maybe someone else can explain it clearer.  your code
looks as if it would work fine too, but strtok is a nicer little
trick i've picked up watching USENET.

____________________}John Flinchbaugh{______________________


~~~~~~~~~~~~microsoftfree==100%linux==100%power~~~~~~~~~~~~~



Fri, 12 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)



 >[Someone's news software is screwed up.  The quoted article has just been
 > filed for approval, but I had *not* sent it out when I got this followup.
 > You can tell because the "In-Reply-To:" header refers to an article that was
 > not sent to the group by the moderator.  *sigh*.
 > -mod]

 >> How are you going to use strtok to remove the newline character?
 >>
 >> Wouldn't it be better to use strchr as in
 >>
 >> #include <stdio.h>
 >> #include <string.h>
 >>
 >> int main()
 >> {
 >>    char name[50],*s;
 >>    
 >>    printf("Your name is ?: ");
 >>    fgets(name,50,stdin);
 >>    s = strchr(name,'\n');
 >>    if(s)
 >>       *s = '\0';
 >>    printf("You enter %s as your name.",name); /* Prints as one line */  
 >>    return 0;
 >> }:
 >
 >you call strtok with the string to tokenize and a string of delimiters.
 >strtok then changes the string you passed it to the first token,
 >EXCLUDING the delimiter (in our case the '\n').  if the delimiter
 >isn't present, the string just stays as it was.
 >
 >give it a try.  maybe someone else can explain it clearer.  your code
 >looks as if it would work fine too, but strtok is a nicer little
 >trick i've picked up watching USENET.

Maybe you picked it up from a bunch who have never written threaded programs
or used strtok() inside a signal handler.

It is an evil, non-reentrant function which uses a global variable to save some
context information in between successive invocations.

I keep it locked up in a jail cell with inmate gets().



Mon, 15 Mar 1999 03:00:00 GMT  
 Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)



Quote:
>you call strtok with the string to tokenize and a string of delimiters.
>strtok then changes the string you passed it to the first token,
>EXCLUDING the delimiter (in our case the '\n').  if the delimiter
>isn't present, the string just stays as it was.

>give it a try.  maybe someone else can explain it clearer.  your code
>looks as if it would work fine too, but strtok is a nicer little
>trick i've picked up watching USENET.

It has also been pointed out on Usenet that the strtok() trick fails if the
line is blank (i.e. consists of just a '\n' character). So its use is
limited.

--
-----------------------------------------


-----------------------------------------



Thu, 25 Mar 1999 03:00:00 GMT  
 
 [ 8 post ] 

 Relevant Pages 

1. Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (0/1)

2. Help, I am new to cprograming and can't figure out why this does not work right. - mail.cpp (1/1)

3. CFile not working properly, can't figure out why (last message not sent properly)

4. Help, I am new to cprograming ...

5. CFile not working properly, can't figure out why

6. Don't know why resourses not working?

7. Figuring out why main form window won't close

8. Getting RegSvr32 registration failed, but can't figure out why

9. Server Error in '/RI' Application

10. Help I cant C what I am doing wrong

11. Help - what am I doing wrong?

12. Help - why is Class Wizard not recognising new dialog controls

 

 
Powered by phpBB® Forum Software