Using Files Inside Switch Statements

This is a discussion on Using Files Inside Switch Statements within the C Programming forums, part of the General Programming Boards category; Hi everyone, I need some urgent help and wondered if anyone would know what I'm doing wrong here. I've got ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Using Files Inside Switch Statements

    Hi everyone, I need some urgent help and wondered if anyone would know what I'm doing wrong here. I've got a project to do where I need to make a basic bot, basically I want the program to (if the user chooses this option) ask the user a series of questions and for the program to save the answers in a file. I've worked out how to do this but can't seem to incorperate it into my program, the problem is it wont save the text. I don't know if it'd be easier to do it in a different way, I'm a real beginner so if you could demonstrate answers it'd be much appreciated. It's the switch 3 that needs to start asking questions. Here's the code.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    	int test_value;	/*declaring the test_value*/
    	char username[20]; /*declaring the username variable*/
    	int mainmenu; /*declaring the mainmenu variable*/
    	int secmenu; /*declaring the second menu variable*/
    	char ansone[30];
    	
    	
    	
    	printf("Welcome to Reading Cinema! Please Enter Your Name: "); /*first printed text, requesting users name*/
    	scanf ("%s", &username); /* reads users name*/
    	test_value=(strcmp (username, "Tom")); /*test value is Tom*/
    
    	if ( test_value == 0 ) /*if user name matches test value then*/
    		printf("Hello %s! Great to see you again!\n", username);
    	else /*if it does not match then*/
    		printf("Hello %s!\n",username);
    	
    	
    	printf(" \nPlease Select From The Following Options: \n 1. Cinema Ticket Prices \n 2. Films on Show \n 3. Film Questionnaire \n");
    	scanf("%d", &mainmenu); /*detects which choice*/
    
    	switch(mainmenu) /*first switch statement*/
    {
    	case 1:{ printf("\nYou Chose Ticket Prices.\nPlease choose from the following:\n1.Adult\n2.Child\n3.Student\n"); break;}
    	case 2:{ printf("\nYou Chose Films on Show.\nPlease choose from the following films to see times:\n4.Watchmen\n5.The Boat That Rocked\n6.Slumdog Millionaire\n7.Paul Blart: Mall Cop\n8.New In Town\n"); break;} 
    	case 3:{ printf("\nThankyou For Agreeing To Take Part In Our Quick Questionnaire!\n"); 
    		{
    		
    		FILE *file_ptr;
    		file_ptr = fopen("answerone.txt", "w");
    
    			
    		printf( "What Is Your Favourite Ever Film?\n" );
    		gets(ansone);
    		fputs(ansone, file_ptr);
    		fclose(file_ptr);
    		}
    		break;}
    }
    	scanf("%d", &secmenu);
    	switch (secmenu)
    {
    
    	case 1:{ printf("\nAdult Ticket Price:\n7 pounds\n"); break;}
    	case 2:{ printf("\nChild Ticket Price:\n5 pounds\n"); break;}
    	case 3:{ printf("\nStudent Ticket Price:\n6 pounds\n"); break;}
    	case 4:{ printf("\nWatchmen\n8.00\n9.00\n12.00\n14.00\n16.00\n20.00\n21.00\n22.00\n"); break;}
    	case 5:{ printf("\nThe Boat That Rocked\n11.00\n12.00\n13.00\n13.30\n16.00\n21.40\n22.00\n23.00\n"); break;}
        case 6:{ printf("\nSlumdog Millionaire\n14.00\n16.00\n20.00\n21.00\n22.00\n"); break;}
    	case 7:{ printf("\nPaul Blart: Mall Cop\n14.00\n16.00\n20.00\n22.30\n23.00\n"); break;}
        case 8:{ printf("\nNew In Town\n11.00\n12.00\n13.00\n16.30\n18.00\n"); break;}
    
    }
    
    
    	return 0;
    			}
    Thanks!

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by arealfind08 View Post
    I've worked out how to do this but can't seem to incorperate it into my program, the problem is it wont save the text.
    That is a little oxymoronic. How have you "worked it out"? Try writing a simple program to write a line of text into a file first; once you can do that you will really have "worked out how to do this".

    You are only making your life difficult by trying to do something you've never done in the context of a larger, more complicated program. Start simple.

    clue: you want to use fopen() and fprintf() (or fwrite()).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Bigger clue:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
    	FILE *fh=fopen("testfile.txt","w");
    	if (!(fh)) { puts("Can't create file."); return -1; }
    	fprintf(fh, "A program called %s created this file.",argv[0]);
    	fclose(fh);
    	return 0;
    }
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    4
    Quote Originally Posted by MK27 View Post
    That is a little oxymoronic. How have you "worked it out"? Try writing a simple program to write a line of text into a file first; once you can do that you will really have "worked out how to do this".
    I have done this, that's why I said I've worked it out, the code is

    Code:
    #include <stdio.h>
    int main()
    {
    	char ansone[30];
    	FILE *file_ptr;
    	file_ptr = fopen("data.txt", "a");
    
    	{
    		printf( "What Is Your Favourite Ever Film?\n" );
    		gets(ansone);
    		fputs(ansone, file_ptr);
    		fclose(file_ptr);
    
    	}
    
    }
    Which is the same as what's been put in my program. This code compiles and runs correctly. Thanks anyway for your overly patronising response!

  5. #5
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by arealfind08 View Post
    This code compiles and runs correctly. Thanks anyway for your overly patronising response!
    Ouch! I'm sorry -- you're right. Lemme compile your code myself and see if I can actually be of assistance...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    This seems to work:
    Code:
    		printf( "What Is Your Favourite Ever Film?\n" );
    		scanf("%s",&ansone);
                    fprintf(file_ptr,"%s",ansone);
    		fclose(file_ptr);
    I don't use fputs() and gcc actually says " warning: the `gets' function is dangerous and should not be used", so I don't know if you were using them correctly or not.

    ps. you might want to use "getchar()" after your scanf("%d") since capturing a number that way will leave a newline in the console buffer -- and that will be the next thing inputed, unless it's eaten by getchar(). scan("%s") gets the newline too, so it's not a problem.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    4
    i've cracked it now with the help of that! thanks very much, all it needed was a scanf before the gets, which is strange because

    1. it doesn't need that in my other program and
    2. my 'Beginners Book' says that scanf wont accept characters with spaces, however that seems to be working fine!

    anyway it's working which is great, thanks again!!

  8. #8
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    Quote Originally Posted by arealfind08 View Post
    2. my 'Beginners Book' says that scanf wont accept characters with spaces, however that seems to be working fine!
    What exactly do you mean by this? . . . scanf() does *not* read in strings that have spaces in them. It's part of the design for scanf(), since it allows you to read in multiple numbers, chars, etc (think "%i %i"). Last time I checked, anyhow . . .

    How does it work? How *is* is working?
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  9. #9
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Quote Originally Posted by Nightowl View Post
    What exactly do you mean by this? . . . scanf() does *not* read in strings that have spaces in them.
    more accuratle will be to say "scanf does not read strings with whitespace when %s format is used", but %s is not the only known format for reading strings, there are others that could give a possibility to read strings with spaces
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You can do this:
    Code:
    scanf("%[a-zA-Z0-9 ]",&string);
    Notice the space. However, the trailing newline problem comes back (there is a preceeding one in your program, btw, from "what is your name"). I had forgotten about the "spaces" issue (sorry again!) because I don't use scanf much, I'd rather just write a function:
    Code:
    int getstring (char *ptr) {
            int ch, i=0;
            while ((ch=fgetc(stdin))!='\n') { ptr[i]=ch; i++; }
            ptr[i]='\0';
            return i;
    }
    But that seemed long winded, so I used the scanf earlier. The nice thing about the function is that if you add one more parameter, you can use it on disk files too.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  11. #11
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    scanf("%[a-zA-Z0-9 ]",&string); - & probably should not be there

    your second function does not checks EOF return value that will indicate some read error or pressing Ctrl-Z/D by user, or end-of-file if stdin was redirected
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by vart View Post
    scanf("%[a-zA-Z0-9 ]",&string); - & probably should not be there
    True. Little strange that works, actually...

    your second function does not checks EOF return value that will indicate some read error or pressing Ctrl-Z/D by user, or end-of-file if stdin was redirected
    It doesn't check to see if we spilled coffee on anything and threw it out the window either! There is a long version -- I was just trying to introduce the possibility, because I think given the choice a clever, competent person would rather customize a function than a conversion specifier template or maybe that's backward...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Switch inside While issues
    By LopsidedElf in forum C Programming
    Replies: 6
    Last Post: 02-16-2009, 02:32 PM
  2. infinite while loop inside a switch statement.
    By tummala_005 in forum C Programming
    Replies: 6
    Last Post: 12-15-2008, 05:46 PM
  3. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 02:30 PM
  4. right use of switch(), case and break statements
    By Niara in forum C++ Programming
    Replies: 4
    Last Post: 01-13-2006, 07:29 AM
  5. switch statements
    By joshua in forum C Programming
    Replies: 3
    Last Post: 11-21-2005, 03:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21