Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

more switch help

Status
Not open for further replies.

rewclaus

Programmer
Mar 7, 2005
16
US
I am trying to create a switch function...this is what I have so far:

switch (fixed)
{
case(1): {
fp1 = fopen("somefile.dat", "w");
printf("\"somefile.dat\"");
while(l<6)
{
for (ctr=(l*10); ctr<((l+1)*10); ctr++)
{fprintf(fp1," %d,", deck[ctr]);}
fputs("\n", fp1);
l++;
}
break;
}
case(2): {
fp2 = fopen("otherfile.dat", "w");
printf("\"otherfile.dat\"");
while(l<6)
{
for (ctr=(l*10); ctr<((l+1)*10); ctr++)
{fprintf(fp2, " %d,", deck[ctr]);}
fputs("\n", fp2);
l++;
}
break;
}
default: break;


But for some reason, when I run this witha menu I have created I get a segmentation error when I choose fixed to be 1. When fixed is 2 it works just fine. I get my file no problems. I have all the variables [fixed, l, and fp1, & fp2] defined, and I have all the closing stuff [return, and fclose]. Could someone give me some help please?

-rewclaus
 
1. Don't use so many braces. The switch statement syntax is much more simpler:
Code:
switch (expression)
{
labelled by case/default labels statement sequence
}
For example:
Code:
switch (fixed)
{
case 1:
   ...
   break;
case 2:
   ...
   break;
default: /* 0/1 occurence */
   ...
}

2. We can't help you because of we don't know what's l var initial value and what's deck array dimension/extent. Probably you get too large index in fprintf's then catch memory access exception...
 
1. Please use [code][/code] tag when posting code.

2. l is a very poor choice for a variable name, it looks too much like 1.

3. Why don't you use a for loop instead of a while loop?
Code:
for ( i = 0 ; i < 6 ; i++ )

4. fp1 = fopen("somefile.dat", "w");
Always check for success.

5. fprintf(fp1," %d,", deck[ctr]);
Your loop iterates 60 times (assuming l starts at 0), yet this strongly suggests you have a deck of cards with the usual 52 entries. Lots of overflow and other nasties here.

Perhaps
Code:
for ( i = 0 ; i < 52 ; i++ ) {
  fprintf(fp2, " %d,", deck[i]);
  if ( (i+1)%10 == 0 ) fputs("\n", fp2);
}

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top